从回调中检索原始上下文

时间:2015-03-24 18:35:37

标签: javascript jquery callback this

我有一个JavaScript类,有两个方法,如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();

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

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

2 个答案:

答案 0 :(得分:1)

您可以使用$.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.other()函数并引用this实例{/ 1}}。

JSFIddle with code in action

答案 1 :(得分:1)

您可以将this传递给eventData的{​​{1}}参数。

.click

你看到你的html对象在其他地方登录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 } }; 的原因是因为其他人正在this回调的上下文中运行而.click指的是它的来电者 - - > html对象。