如何妥善处理类中this指向与removeListener的适配问题?
类中
this指向与事件监听器removeListener的适配方案探讨 通常我们可以使用箭头函数在类中维护this指向,示例代码如下:
class Test { constructor() { browser.tabs.onUpdated.addListener((...e) => this.process(...e)); } process() { // some code this.run(); } run() { // some code } }
但这种方式无法配合removeListener使用,此时可以借助bind解决:
class Test { constructor() { this.process = this.process.bind(this); if (preference) { browser.tabs.onUpdated.addListener(this.process); } else { browser.tabs.onUpdated.removeListener(this.process); } } process() { // some code this.run(); } run() { // some code } }
虽然重复的事件监听器会被忽略,但bind每次都会创建新函数,在background service worker(或event page)场景下,每次重启都可能生成新的监听器。此外,也可以使用类名替代this来避免使用bind。
请问是否存在更优的方案来处理this指向与removeListener的适配问题?
内容的提问来源于stack exchange,提问作者erosman
相关产品推荐
相关产品推荐

