如何防止“;这个“;防止被事件处理程序反弹

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

本文关键字:事件处理 程序 何防止 这个      更新时间:2023-09-26

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

我已经尝试过将函数bind绑定到this,它被绑定到窗口,而不是对象的实例。

我想要的示例:在这个演示中(下面重复代码),我想要一个点击按钮时显示"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调用函数更好的方法,因为他们不需要如此深入地理解您的类。