被覆盖的“这个”变量问题还是如何调用成员函数? [英] Overwritten "this" variable problem or how to call a member function?
本文介绍了被覆盖的“这个”变量问题还是如何调用成员函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
var MyClass = Class.create({
initElements:function(sumEl)){
this.sumEl = sumEl ;
sumEl.keyup(this.updateSumHandler);
},
updateSumHandler:function(event){
//在这里抛出错误:this.updateSum是不是一个函数
this.updateSum();
},
updateSum:function(){
//在这里做某事
}
});
如何调用 this.updateSum()
毕竟?
解决方案
你需要使用闭包。
initElements:function(sumEl){
this.sumEl = sumEl;
var ref = this;
sumEl.keyup(function(){ref.updateSumHandler();});
},
I have this class where I am using a combination of jQuery and Prototype:
var MyClass = Class.create({
initElements: function(sumEl) {
this.sumEl = sumEl;
sumEl.keyup(this.updateSumHandler);
},
updateSumHandler: function(event) {
// Throws error here: "this.updateSum is not a function"
this.updateSum();
},
updateSum: function() {
// does something here
}
});
How can I call this.updateSum()
after all?
解决方案
You need to use closures.
initElements: function(sumEl) {
this.sumEl = sumEl;
var ref = this;
sumEl.keyup( function(){ref.updateSumHandler();});
},
这篇关于被覆盖的“这个”变量问题还是如何调用成员函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文