Here is the code
function Person(name, age, weight) {
this._name = name;
this._weight = weight;
this._age = age;
}
Person.prototype = {
Anatomy: {
Weight: this._weight,
Height: (function () {
//calculate height from age and weight
})
}
}
i expected Anatomy.weight to be 60 when i ran this code:
var x = new Person('jack',24,60);
console.dir(x.Anatomy);
To my surprise it was undefined. On inspection it seemed that this was referring to global object window. Now what has happened here 🙁
I expected this._weight to refer Person objects weight, otherwise from rough calculation, this should have at the least referred to Anatomy since it is a object. Could someone clarify the doubt
You can’t to that.
thisis only available in functions. Where you used it, it refers to the global object. A possible solution would be this:I don’t know if this is the best solution, but it’s the best that I can think of right now.