Javascript回调丢失“this” [英] Javascript callbacks losing 'this'

查看:123
本文介绍了Javascript回调丢失“this”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个签发者,我在这个'对象'里面失去了'这'。下面的javascript的输出给我some-id,然后未定义。当我在回调函数中使用'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);
}

bind 但是这不是在每个浏览器都可用,并且似乎你使用jQuery我使用jQuery等效 $。proxy

这篇关于Javascript回调丢失“this”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆