如何防止 "this" 被事件处理程序反弹

How to prevent "this" from being rebound by event handlers

我有一个 JS 对象,它的原型函数之一是单击事件处理程序。调用该函数时,this 对象将设置为单击绑定到的元素。我希望 this 成为函数所属对象的实例。这可能吗?如果可以,我该怎么做?有或没有 jQuery 的解决方案对我来说都是可以接受的,尽管我确信 SO 的其余部分会喜欢纯 JS 解决方案。

我试过 binding the function to this,它绑定到 window 而不是对象的实例。

我想要的示例:在this demo(下面重复的代码)中,我想要在单击按钮时显示"Bark" 的警报。

var Dog = function () {
    this.sound = "Bark";
}

Dog.prototype = {
    sayHello: function (e) {
        if (typeof this.sound == "undefined") {
            alert("I don't know what sound I should make!\n" + this);
        } else {
            alert(this.sound);
        }
    }
}

var d = new Dog();
var elem = document.getElementById("click");
elem.addEventListener("click", d.sayHello);

您可以这样使用 .bind()

elem.addEventListener("click", d.sayHello.bind(d));

手动执行此操作的方法是使用您自己的函数:

elem.addEventListener("click", function(e) {
    return d.sayHello();
});

如果您总是希望使用自己的上下文调用函数,请在构造函数运行时进行绑定:

var Dog = function () { 
  this.sound = "Bark";
  this.sayHello = this.sayHello.bind(this);
}

http://jsfiddle.net/04ykpsx1/1/

类似 _.bindAll 的内容可以为您减少样板文件。

这比强制调用者始终使用 .bind 调用函数更好,因为他们不需要如此深入地了解您的 class。