You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何妥善处理类中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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.11 05:10:22