我想使用事件处理函数作为Javascript对象的一部分。我希望将事件处理程序中的"this“绑定到它的方法所在的对象,因为事件处理程序中的"this”通常会自动分配给发生事件的对象。
var myObject = {
init:function(){
this.downHandler = this.downHandler.bind(this);
},
downHandler:function(){
alert(this.someInfo);
},
someInfo:"hi there"
}
myObject.init();我想避免这种情况:在其他地方重新定义它会降低代码的可维护性。所以我在寻找一种解决方案,将绑定过程保持在方法本身。
我已经尝试过立即执行函数,但在立即执行时,"this“指向"window”对象(假设是browser-context)。我的试验是这样的:
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
} 发布于 2012-11-18 00:19:29
由于您已经使用jQuery.proxy加载了jQuery
var myObject = {
downHandler: $.proxy(function(){
alert(this.someInfo);
}, this)
};如果您已经安装了Underscore (对于这样的东西,我更喜欢使用它),请使用_.bind
var myObject = {
downHandler: _.bind(function(){
alert(this.someInfo);
}, this
};MooTools可能也有类似的东西--我从未考虑过使用它。
发布于 2012-11-18 00:21:09
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-18 00:50:36
在警报期间,请使用对象名称'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"
} 我希望这能对你有所帮助。
https://stackoverflow.com/questions/13432190
复制相似问题