我想从一个类中调用一个类函数,该类函数我之前已附加到驻留在该类中的按钮对象上(以下代码有效,但callMyClassFunction中的作用域位于按钮上,并且我希望它是Carousel):
//Examplecode 1
Carousel.prototype.addEventListeners = function(){
this.button.on('click', this.callMyClassFunction);
}
Carousel.prototype.callMyClassFunction = function(){
console.log(this);
}
如果我像这样绑定函数,它就会起作用(它的范围是类实例):
//Examplecode 2
Carousel.prototype.addEventListeners = function(){
this.button.on('click', function(){
this.callMyClassFunction()
}).bind(this);
}
但是我宁愿为click-eventlistener添加一个引用(例如在Examplecode 1中),因为我想在另一个函数中调用removeListener:
//Examplecode 3
Carousel.prototype.removeEventListeners = function(condition){
if(condition){
this.button.removeListener('click', this.callMyClassFunction);
}
}
任何帮助深表感谢!
只需将绑定的侦听器存储在您的实例上:
functin Carousel(…) {
…
this.callMyClassFunction = this.callMyClassFunction.bind(this);
}
Carousel.prototype.callMyClassFunction = function(){
console.log(this);
};
Carousel.prototype.addEventListeners = function(){
this.button.on('click', this.callMyClassFunction);
};
Carousel.prototype.removeEventListeners = function(…){
…
this.button.removeListener('click', this.callMyClassFunction);
};
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句