【问题标题】:Retrieve origina context from callback从回调中检索原始上下文
【发布时间】:2015-03-24 18:35:36
【问题描述】:

我有一个带有两个方法的 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();

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

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

【问题讨论】:

    标签: javascript jquery callback this


    【解决方案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 实例引用MyObject

    JSFIddle with code in action

    【讨论】:

      【解决方案2】:

      您可以将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 的原因是因为 other 在 .click 回调的上下文中运行,而 this 指的是它的调用者 --> html 对象。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-03-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-12-19
        相关资源
        最近更新 更多