将类实例方法作为参数传递时,如何保留函数上下文?
类实例方法赋值后上下文丢失的解决方案
当你把类实例的this.post赋值给变量或者作为参数传递后调用时,会因为this上下文丢失导致报错,以下是几种直接可行的解决办法:
1. 用bind强制绑定上下文
bind方法会返回一个新函数,将原函数的this永久绑定到指定对象,后续调用这个新函数时this不会改变:
class MyClass { async myFunc(){ await this.post(...) // 正常运行 // 绑定当前实例的this到post方法 const postCopy = this.post.bind(this) await postCopy(...) // 正常运行 // 作为参数传入时同样用bind处理 someOtherFunction(this.post.bind(this)) } }
2. 用箭头函数包裹捕获上下文
箭头函数没有自己的this,会继承外层作用域的this,用它包裹原方法可以保留当前实例的上下文:
class MyClass { async myFunc(){ await this.post(...) // 正常运行 // 箭头函数捕获当前myFunc作用域的this const postCopy = (...args) => this.post(...args) await postCopy(...) // 正常运行 // 作为参数传入时直接传递箭头函数 someOtherFunction((...args) => this.post(...args)) } }
3. 提前用箭头函数定义类方法
如果post方法不需要动态切换this,可以在类定义阶段就用箭头函数声明方法,这样实例化后方法的this会永久绑定到当前实例:
class MyClass { // 用箭头函数定义post方法,this固定为当前实例 post = async (...args) => { // 原post方法的业务逻辑 } async myFunc(){ await this.post(...) // 正常运行 const postCopy = this.post await postCopy(...) // 正常运行 // 直接作为参数传入即可 someOtherFunction(this.post) } }
内容的提问来源于stack exchange,提问作者Drico
相关产品推荐
相关产品推荐

