我有一个发布者,我在这个对象中丢失了 this
。以下 JavaScript 片段的输出为我提供了 "some-id"
,然后是 undefined
。当我在回调函数中使用 this
时,范围超出了对象,它不能再使用 this
了。我怎样才能让回调使用“this”或至少可以访问该对象?
因为我会制作多个对象,所以我无法创建像存储这样的“静态”。
这是我的测试代码,您可以使用它来重现我的问题。我想要的是 CheckBox.doSomething()
返回 this.id
的值,该值应该与此测试的 some-id
匹配案例。
function CheckBox(input_id) {
this.id = input_id;
this.doSomething();
$('#some-element').click(this.doSomething);
}
Checkbox.prototype.doSomething = function() {
alert(this.input_id);
}
var some_box = new CheckBox('some-id');
some_box.doSomething();
$('#some-element').click();
我什至不能让它按照我想要的那样工作:
function CheckBox2(input_id) {
this.id = input_id;
alert(this.id);
}
CheckBox2.prototype.doSomething = function() {
alert(this.input_id);
}
var some_box = new CheckBox2('some-id');
some_box.doSomething();
最佳答案
您的问题出在这一行:$('#some-element').click(this.doSomething);
为什么这是个问题
JavaScript 方法对应该分配给 this
的对象一无所知,它是在显式调用方法时设置的(使用 myFunction.call(obj)
) 或隐式(使用 obj.myFunction()
调用时)。
例如:
var x = {
logThis: function () {
console.log(this);
}
};
x.logThis(); // logs x
x.logThis.call(y); // logs y
var func = x.logThis;
func(); // logs window: the fallback for when no value is given for `this`
在您的例子中,您将 this.doSomething
传递给 jQuery,然后 jQuery 使用被单击的元素作为 this
的值显式调用它。发生的事情是(稍微复杂一点的)这个:
var callback = this.doSomething;
callback.call(anElement, anEvent);
解决方案
您需要确保使用正确的 this
值调用 doSomething
。您可以通过将其包装在另一个函数中来做到这一点:
var cb = this;
$('#some-element').click(function() {
return cb.doSomething();
});
jQuery 提供了一个 proxy
函数可以让你更简单地做到这一点:
$('#some-element').click(jQuery.proxy(this.doSomething, this));
关于Javascript 回调丢失 'this',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10766407/