Today I Learned - Rocky Kev

TIL JS Constructors

POSTED ON:

TAGS:

The constructor

function gameCharacter (name, xPos, health) {
    this.name = name;
    this.xPos = xPos;
    this.health = health;
    this.move = function(x) {
        this.xPos += x;
    };
    this.class = "Wizard";
}

Create a new version of gameCharacter, and modify it's values.

var gc1 = new gameCharacter("Nimish", 0, 100);

var name = gc1.name;
gc1.health = 150;
gc1.move(10);

QUESTION: Can I add new things?
OF COURSE!

gc1.yPos = 5;
gc1.randomFunction = function(x) {
    return "Works";
}

But it doesn't get effect the gameCharacter() function, since it's specifically for gc1.
Example:

var gc2 = new gameCharacter("Yolo", 5, 150);
gc2.yPos; //reference error

QUESTION: How do you add additional functions to your class?
WiTH PROTOTYPE!

//add new element
gameCharacter.prototype.class = "Wizard";

//call element
gc1.class; //"Wizard"
gc2.class; //"Wizard"
gc1.class = "Barbarian"; //changes to Barbarian for gc1

//Add function
var heal = function(healamount) {
    this.health += healamount;
}

//call function
gameCharacter.prototype.heal = heal;
gc1.heal(5); //adds 5 to health for gc1
gc2.heal(10); //adds 10 to health for gc2

Related TILs

Tagged:

TIL what is npm Script

Despite their high usage they are not particularly well optimized and add about 400ms of overhead. In this article we were able to bring that down to ~22ms.

TIL fancy methods to transform Javascript Objects

You can use Object.entries(), Object.keys(), Object.fromEntries()...

TIL how to hide your JS code

ONE THING TO NOTE: Encrypting a script is stronger than obfuscation, both methods are still not adequate to protect secret content. Honestly, I don't think it's worth it on a production site, and instead just go with pure server-side if you want security. But it's fascinating.