在此代码中:
MyClass.prototype = {
methodA: function() {
var obj = this;
$('#my-field').keyup(function(){
obj.methodB();
});
},
methodB: function() {
var obj = this;
$('.flag').click(function(){
obj.methodC($(this), $(this).attr('data-id-flag'));
obj.methodD();
});
},
...
}
有没有办法删除某些方法中存在的以下多重声明?
var obj = this;
我必须使用此原因解释in this question。
答案 0 :(得分:2)
我认为你的意思是如何将上下文传递给那些闭包。
您可以使用.bind(this)
或$.proxy(function(){}, this)
。
MyClass.prototype = {
methodA: function() {
$('#my-field').keyup($.proxy(function(){
this.methodB();
}, this));
},
methodB: function() {
$('.flag').click($.proxy(function(e){
var $el = $(e.currentTarget);
this.methodC($el, $el.attr('data-id-flag'));
this.methodD();
}, this));
},
}