function Person(gender) {
this.gender = gender;
}
Person.prototype.sayGender = function()
{
alert(this.gender);
};
var person1 = new Person('Male');
var genderTeller = person1.sayGender;
person1.sayGender(); // alerts 'Male'
genderTeller(); // alerts undefined
Why does genderTeller(); alerts undefined is not clear to me. if I see it I believe it’s just same as line above it. Can some please explain the details
When you assign a variable like this…
…you lose the context of the
person1object, and the function’sthispoints to the global object (windowin a browser), instead of the instantiatedperson1object.You get
undefinedbecause thegenderproperty does not exist onwindow, and referencing an undefined property on an object returnsundefinedin JavaScript.You can fix that in modern browsers with
bind()……or jQuery has a method too called
proxy().