我想使用事件处理函数作为 Javascript 对象的一部分。我想将事件处理程序中的“this”绑定到它是一种方法的对象,因为事件处理程序中的“this”通常会自动分配给事件发生的对象。
这可以通过对发生绑定的对象使用 init 函数来完成(jsfiddle 用于 tryout):
var myObject = {
init:function(){
this.downHandler = this.downHandler.bind(this);
},
downHandler:function(){
alert(this.someInfo);
},
someInfo:"hi there"
}
myObject.init();
我想避免这种情况:在其他地方重新定义它会降低代码的可维护性。所以我正在寻找一种解决方案,将绑定过程保持在方法本身。
我已经尝试过立即执行函数,但是在立即执行时,“this”指向“window”对象(假设浏览器上下文)。我的试验看起来像这样:
var myObject = {
//more code
downHandler:(function(){
alert(this.someInfo);
}).bind(this), //does not work since at the point of immediate execution, the this is assigned to window
//more code
}
您能想出一种将绑定保留在事件处理函数而不是单独的初始化函数中的方法吗?