从回调中检索原始上下文

Retrieve origina context from callback

我有一个 JavaScript class 有两种方法,例如 this.

var MyObject = function () {};

MyObject.prototype = {
    open: function () {
        var self = this;
        console.log(self);

        $('#a').click('', self.other);
    },
    other: function () {
        console.log(this);
    }
};

var myobject = new MyObject;

myobject.open();

other函数中的console.log中,this是事件监听的HTML节点,而不是MyObject中的对象open 函数。

当用作回调时,如何从函数 other 中检索 MyObject 对象?

您可以使用 $.proxy 传递 this 上下文作为第二个参数:

var MyObject = function () {};

MyObject.prototype = {
    open: function () {
        $('#a').click($.proxy(this.other, this));
    },
    other: function () {
        console.log(this);
    }
};

var myobject = new MyObject;

myobject.open();

单击 #a 时,将使用引用 MyObject.

this 实例调用 MyObject.other() 函数

JSFIddle with code in action

您可以将 this 传递给 .clickeventData 参数。

MyObject.prototype = {
    open: function () {
        var self = this;
        console.log(self);

        $('#a').click(self, self.other);
    },
    other: function (event) {
        console.log(event.data); // should output your object
    }
};

您看到 html 对象在 other 中记录 this 的原因是因为在 .click 回调和 this 指的是它的调用者 --> html 对象。