为什么方法的`this`在调用对象方法的引用时会改变? [英] Why does a method's `this` change when calling a reference to an object's method?
问题描述
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
为什么genderTeller();警报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...
var genderTeller = person1.sayGender;
...你丢失了上下文 > person1
object,函数的 this
指向全局对象( window
in a浏览器),而不是实例化的 person1
对象。
...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.
你得到 undefined
因为窗口
上不存在 gender
属性,并且引用对象上的未定义属性返回< JavaScript中的code> undefined 。
You get undefined
because the gender
property does not exist on window
, and referencing an undefined property on an object returns undefined
in JavaScript.
您可以使用 bind()
...
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);
这篇关于为什么方法的`this`在调用对象方法的引用时会改变?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!