1

我想使用事件处理函数作为 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
}      

您能想出一种将绑定保留在事件处理函数而不是单独的初始化函数中的方法吗?

4

3 回答 3

2

既然您已经加载了 jQuery,请使用jQuery.proxy

var myObject = {
    downHandler: $.proxy(function(){
       alert(this.someInfo);
    }, this)
};

如果你已经安装了下划线(我更喜欢这样的东西),使用_.bind

var myObject = {
    downHandler: _.bind(function(){
       alert(this.someInfo);
    }, this
};

MooTools 可能也有类似的东西——我从来没有考虑过使用它。

于 2012-11-17T16:19:29.273 回答
0
var myObject = {
    clickHandler: function() {
        alert(myObject.someInfo); 
        //returns undefined without execution of init-function
        //returns "hi there" if init ran. 
    },
    someInfo: "hi there"
}

$('#clickMe').on('click', myObject.clickHandler);
于 2012-11-17T16:21:08.997 回答
0

在警报期间使用对象名称“myObject”而不是“this”。

var myObject = {
    downHandler:(function(){
        alert(myObject.someInfo);
    }).bind(this), 
  //when 'this' use it alert undefined
  //when 'myObject' use it alert "hi there"
   someInfo:"hi there" 
}   

我希望这能帮到您。

于 2012-11-17T16:50:36.353 回答