如何将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
相关产品推荐
相关产品推荐

