Why does a method's `this` change when calling a reference to an object's method?

后端 未结 3 1712
长发绾君心
长发绾君心 2020-12-11 17:43
function Person(gender) {
  this.gender = gender;
}

Person.prototype.sayGender = function()
{
  alert(this.gender);
};

var person1 = new Person(\'Male\');
var gend         


        
3条回答
  •  猫巷女王i
    2020-12-11 18:12

    When you assign a variable like this...

    var genderTeller = person1.sayGender;
    

    ...you lose the context of the person1 object, and the function's this points to the global object (window in a browser), instead of the instantiated person1 object.

    You get undefined because the gender property does not exist on window, and referencing an undefined property on an object returns undefined in JavaScript.

    You can fix that in modern browsers with bind()...

    var genderTeller = person1.sayGender.bind(person1);
    

    ...or jQuery has a method too called proxy().

    var genderTeller = $.proxy(person1.sayGender, person1);
    

提交回复
热议问题