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

如何将Typescript类中的箭头函数改写为普通函数

改写方案

你需要修改的是getAsset方法then回调中的箭头函数,该函数内没有引用外层this,直接将箭头函数声明替换为普通function声明即可,完整修改后代码如下:

class Ratchet extends APlugin<CentralizerConfigPluginRatchet> {
  public search = (): Promise<CentralizerNotif[]> => {throw Error("Not implemented");};

  public notif =
  (): Promise<CentralizerNotif[]> => {
    const toto = new RatchetLib.RatchetAPI(this.config.baseurl);
    // 原箭头函数已改为普通函数
    return toto.getAsset({validation: true}).then(function(result) {
      return [{
        name: `You ${result.assets.length} things to moderate `,
        link: "https://www.exemple.com",
      }];
    });
  };
}

补充注意事项

  • 如果后续你需要在该回调内访问类实例属性,需要手动绑定上下文,有两种实现方式:
    • 给普通函数绑定外层this:
      return toto.getAsset({validation: true}).then(function(result) {
        // 此处可正常访问this
        console.log(this.config.baseurl)
        return [{
          name: `You ${result.assets.length} things to moderate `,
          link: "https://www.exemple.com",
        }];
      }.bind(this));
      
    • 在外层提前存储this引用,回调内通过存储的变量访问:
      const toto = new RatchetLib.RatchetAPI(this.config.baseurl);
      const that = this;
      return toto.getAsset({validation: true}).then(function(result) {
        // 此处通过that访问实例属性
        console.log(that.config.baseurl)
        return [{
          name: `You ${result.assets.length} things to moderate `,
          link: "https://www.exemple.com",
        }];
      });
      
  • 如果你需要同时把notif本身的属性箭头函数改为类普通方法,可参考如下写法:
    public notif(): Promise<CentralizerNotif[]> {
      const toto = new RatchetLib.RatchetAPI(this.config.baseurl);
      return toto.getAsset({validation: true}).then(function(result) {
        return [{
          name: `You ${result.assets.length} things to moderate `,
          link: "https://www.exemple.com",
        }];
      });
    }
    

内容的提问来源于stack exchange,提问作者SuperAzymuth

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 12:24:00