TIL JS Constructors
POSTED ON:
TAGS: javascript basics
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: javascript