58

在回调函数中引用我的对象时,我在使用普通的旧 JavaScript(无框架)时遇到了一些麻烦。

function foo(id) {
    this.dom = document.getElementById(id);
    this.bar = 5;
    var self = this;
    this.dom.addEventListener("click", self.onclick, false);
}

foo.prototype = {
    onclick : function() {
        this.bar = 7;
    }
};

现在,当我创建一个新对象时(在 DOM 加载后,使用 span#test)

var x = new foo('test');

onclick 函数中的“this”指向 span#test 而不是 foo 对象。

如何在 onclick 函数中获取对我的 foo 对象的引用?

4

7 回答 7

81

(提取了一些隐藏在其他答案的评论中的解释)

问题在于以下行:

this.dom.addEventListener("click", self.onclick, false);

在这里,您传递一个函数对象以用作回调。当事件触发时,该函数被调用,但现在它与任何对象(this)都没有关联。

该问题可以通过将函数(及其对象引用)包装在闭包中来解决,如下所示:

this.dom.addEventListener(
  "click",
  function(event) {self.onclick(event)},
  false);

因为变量 self 在创建闭包时被赋值,所以闭包函数会在以后调用时记住 self 变量的值。

解决这个问题的另一种方法是创建一个实用函数(并避免使用变量来绑定this):

function bind(scope, fn) {
    return function () {
        fn.apply(scope, arguments);
    };
}

更新后的代码将如下所示:

this.dom.addEventListener("click", bind(this, this.onclick), false);

Function.prototype.bind是 ECMAScript 5 的一部分并提供相同的功能。所以你可以这样做:

this.dom.addEventListener("click", this.onclick.bind(this), false);

对于还不支持 ES5 的浏览器,MDN 提供了以下 shim

if (!Function.prototype.bind) {  
  Function.prototype.bind = function (oThis) {  
    if (typeof this !== "function") {  
      // closest thing possible to the ECMAScript 5 internal IsCallable function  
      throw new TypeError("Function.prototype.bind - what is trying to be bound is not callable");  
    }  

    var aArgs = Array.prototype.slice.call(arguments, 1),   
        fToBind = this,   
        fNOP = function () {},  
        fBound = function () {  
          return fToBind.apply(this instanceof fNOP  
                                 ? this  
                                 : oThis || window,  
                               aArgs.concat(Array.prototype.slice.call(arguments)));  
        };  

    fNOP.prototype = this.prototype;  
    fBound.prototype = new fNOP();  

    return fBound;  
  };  
} 
于 2008-10-11T08:33:30.163 回答
15
this.dom.addEventListener("click", function(event) {
    self.onclick(event)
}, false);
于 2008-10-08T15:00:41.313 回答
5

For the jQuery users looking for a solution to this problem, you should use jQuery.proxy

于 2011-01-14T09:44:27.700 回答
2

解释是,self.onclick这并不意味着您认为它在 JavaScript 中的含义。它实际上是指onclick对象原型中的函数self(不以任何方式引用self自身)。

JavaScript 只有函数,没有像 C# 那样的委托,所以不可能传递一个方法和它应该作为回调应用的对象。

在回调中调用方法的唯一方法是在回调函数中自己调用它。因为 JavaScript 函数是闭包,所以它们能够访问在创建它们的范围内声明的变量。

var obj = ...;
function callback(){ return obj.method() };
something.bind(callback);
于 2008-10-11T09:54:00.813 回答
2

此处提供了对该问题的一个很好的解释(到目前为止,我在理解解决方案时遇到了问题)。

于 2009-11-27T17:27:43.767 回答
1

我写了这个插件...

我认为这会很有用

jquery.callback

于 2009-04-16T20:57:54.830 回答
-3

this 是 JS 最令人困惑的地方之一:“this”变量表示最局部的对象……但函数也是对象,所以“this”指向那里。还有其他微妙的地方,但我不记得全部了。

我通常避免使用“this”,只需定义一个本地“me”变量并使用它。

于 2008-10-08T15:10:08.177 回答