我有一些代码.. ala
$.fn.someObj= function(){
this.opt = {
whatever : 'somevalue',
whateve2 : 'more values'
}
this.someMethod = function(){
//do something
$(someElem).bind('click',function(){
this.someOTHERMethod(); <----- ISSUE HERE
})
}
this.someOTHERMethod = function(){
// do more stuff
}
this.init = function(data){
$.extend(this.opt, data);
this.someMethod();
};
};
我可以创建一个闭包并解决问题;
var that = this;
//code
that.someOTHERMethod(); <--- works
或如果我从方法中删除“this”:
someOTHERMethod = function(){}
and just call it: someOTHERMethod(); < ---- works
但我想知道是否有一种更优雅的方式来获得没有封闭的外部功能或?有什么想法吗?
答案 0 :(得分:1)
当您使用jQuery时,您应该使用$.proxy
$(someElem).on('click', $.proxy(this, 'someOTHERMethod'));
答案 1 :(得分:1)
你不需要一个闭包,你只需要传递对你的函数的引用,并消除包装器的匿名函数:
$(someElem).on('click', this.someOTHERMethod);
如果您希望this
内的someOTHERMethod
值为someObj
,请根据zzzzBov的回答使用$.proxy
。