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

后端 未结 3 1708
长发绾君心
长发绾君心 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条回答
  •  不思量自难忘°
    2020-12-11 18:20

    You are calling the function without the context of its object, so this will be the global object window, so the function alerts the value of window.gender, which is undefined.

提交回复
热议问题