JavaScript传递函数时this绑定丢失,求更优雅解决方案
解决类方法返回函数时this绑定丢失的问题
问题复现
定义如下类,其中getFunc方法返回一个供第三方调用的函数,尝试在该函数内调用类成员时,this丢失了类实例的绑定:
class myclass { printIt(x) { console.log(x); } getFunc() { return function(x) { this.printIt(x); }; } } (new myclass).getFunc()("test");
执行后抛出错误:
TypeError: Cannot read properties of undefined (reading 'printIt')
你当前使用了self = this的方案规避问题,但希望有更优雅的实现方式:
class myclass { printIt(x) { console.log(x); } getFunc() { let self = this; return function(x) { self.printIt(x); }; } } (new myclass).getFunc()("test");
更优雅的解决方案
方案1:使用箭头函数
箭头函数不会创建独立的this上下文,会直接继承外层作用域(即getFunc执行时的类实例this),写法简洁直观:
class myclass { printIt(x) { console.log(x); } getFunc() { return (x) => { this.printIt(x); }; } } (new myclass).getFunc()("test"); // 输出 "test"
方案2:用bind()显式绑定this
通过Function.prototype.bind()将返回函数的this强制绑定到当前类实例,适合需要保留函数独立作用域的场景:
class myclass { printIt(x) { console.log(x); } getFunc() { return function(x) { this.printIt(x); }.bind(this); } } (new myclass).getFunc()("test"); // 输出 "test"
方案3:将类方法定义为箭头函数(提前绑定)
如果printIt不需要动态this,可以直接在类中用箭头函数定义该方法,让它的this永久绑定到类实例:
class myclass { printIt = (x) => { console.log(x); } getFunc() { return function(x) { this.printIt(x); }; } } (new myclass).getFunc()("test"); // 输出 "test"
注意:该方案依赖ES2022+的类字段语法,旧环境需通过转译工具兼容。
内容的提问来源于stack exchange,提问作者Veda
相关产品推荐
相关产品推荐

