function Hero() {
this.occupation = 'Ninja';
}
don’t understand the meaning of this line ,this.occupation = ‘Ninja’; why it use this keyword. thank you.
function Hero() {
this.occupation = 'Ninja';
}
don’t understand the meaning of this line ,this.occupation = ‘Ninja’; why it use this keyword. thank you.
The function in your example is set up to act as a constructor for Hero objects. If it is called with the ‘new’ keyword, it will return an object.
// define a constructor for Hero objects.
// notice the capital H for the function name.
function Hero() {}
// use the constructor to create a Hero instance
var myHero = new Hero();
// myHero now points to an instance of the Hero 'class'
alert(myHero instanceof Hero); // true
Within the constructor, ‘this’ refers to the object that will be returned. It can be used to add properties to the object.
function Hero() {
this.occupation = 'Ninja';
}
var myHero = new Hero();
alert(myHero instanceof Hero); // still true
// use the property set in the constructor
alert(myHero.occupation); // Ninja
The constructor can accept arguments to be used to initialise the object returned
function Hero(job) {
this.occupation = job;
}
var myHero = new Hero("Ninja");
var yourHero = new Hero("Estate Agent");
alert(myHero.occupation); // Ninja
alert(yourHero.occupation); // Estate Agent