Javascript回调丢失'this' [英] Javascript callbacks losing 'this'
问题描述
我有一个发行者,我丢失了这个对象"中的这个".下面一段 javascript 的输出给了我some-id"然后是undefined".当我在回调函数中使用 'this' 时,作用域超出对象并且不能再使用 'this'.如何让回调使用this"或至少可以访问该对象?
I have an issuer where I lose the 'this' inside this 'object'. The output of the following piece of javascript gives me "some-id" and then "undefined". When I use 'this' inside a callback function, the scope goes out of the object and it cannot use 'this' anymore. How can I get the callback to use 'this' or at least have access to the object?
由于我将创建多个对象,因此我将无法创建类似静态"的存储.请帮助这个javascript n00b ;-)
Since I will make multiple objects, I won't be able to create a 'static' like storage. Please help this javascript n00b ;-)
这是我的测试代码,您可以使用它来重现我的问题.我想要的是 CheckBox.doSomething()
返回 this.id
的值,该值应该与此测试的 some-id
匹配案件.
here is my test code that you can use to reproduce my problem. What I would like to have is CheckBox.doSomething()
to return the value of this.id
which should match some-id
for this test case.
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();
我什至无法让它按照我的意愿工作:
edit: I can't even get this to work as I want it to:
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();
推荐答案
function CheckBox(input_id) {
this.id = input_id;
this.doSomething = $.proxy( this.doSomething, this );
$('#some-element').click(this.doSomething);
}
javascript 等价物"是 Function#bind
但并非在每个浏览器中都可用,而且由于您似乎在使用 jQuery,因此我使用的是 jQuery 等价物 $.proxy代码>
The "javascript equivalent" of this is Function#bind
but that is not available in every browser and since it seems you are using jQuery I am using the jQuery equivalent $.proxy
这篇关于Javascript回调丢失'this'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!