Javascript回调失去'这个'

Any*_*one 13 javascript scope object callback this

我有一个发行人,我在这个'对象'中失去了'this'.以下javascript的输出给了我"some-id"然后"undefined".当我在回调函数中使用'this'时,范围会超出对象,并且不再使用'this'.如何让回调使用'this'或者至少可以访问该对象?

由于我将创建多个对象,因此我无法创建像存储一样的"静态".请帮助这个javascript n00b ;-)

这是我的测试代码,您可以用它来重现我的问题.我想要的是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();
Run Code Online (Sandbox Code Playgroud)

编辑:我甚至无法让它按照我的要求工作:

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();
Run Code Online (Sandbox Code Playgroud)

geo*_*ock 17

你的问题在于这一行: $('#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`
Run Code Online (Sandbox Code Playgroud)

在你的情况下,你传递this.doSomething给jQuery,然后使用被点击的元素显式调用它this.发生了什么(稍微复杂一点):

var callback = this.doSomething;
callback.call(anElement, anEvent);
Run Code Online (Sandbox Code Playgroud)

解决方案

您需要确保doSomething使用正确的值调用this.您可以通过将其包装在另一个函数中来实现:

var cb = this;
$('#some-element').click(function() {
    return cb.doSomething();
});
Run Code Online (Sandbox Code Playgroud)

jQuery提供了一个proxy函数,让您可以更简单地执行此操作:

$('#some-element').click(jQuery.proxy(this.doSomething, this));
Run Code Online (Sandbox Code Playgroud)


Esa*_*ija 11

function CheckBox(input_id) {
    this.id = input_id;
    this.doSomething = $.proxy( this.doSomething, this );
    $('#some-element').click(this.doSomething);
}
Run Code Online (Sandbox Code Playgroud)

这个"javascript等价" Function#bind但是在每个浏览器中都没有,因为看起来你正在使用jQuery我使用的是jQuery等价物$.proxy