JavaScript中如何将类方法作为回调传递给另一个类并正确保留this指向
解决类回调中
this绑定丢失的问题 你遇到的问题非常典型——当把类的方法作为回调传递给另一个类时,this的上下文会丢失,导致无法访问原类实例的属性。好在有几种优雅的解决方案,完全能保持两个类的复用性,同时实现数据传递和处理:
方案1:用箭头函数包裹回调
箭头函数会自动继承外层作用域的this,所以在传递回调时用箭头函数包裹,就能确保endMethod里的this指向当前foo实例:
class foo{ constructor(){ this.prroperty = 'yes'; } eventMethod(){ let eventForm = new bar(); // 箭头函数保留foo实例的this上下文 eventForm.fire((value) => this.endMethod(value)); } endMethod(values){ console.log(values + this.prroperty); // 输出 "messageyes" } } class bar{ constructor(){ this.property = 'no'; } fire(callback){ let value = 'message'; callback(value); } }
方案2:用bind()显式绑定this
通过Function.prototype.bind()方法,把endMethod和当前foo实例强制绑定,这样无论在哪里调用这个回调,this都不会跑偏:
class foo{ constructor(){ this.prroperty = 'yes'; } eventMethod(){ let eventForm = new bar(); // 显式绑定this到当前foo实例 eventForm.fire(this.endMethod.bind(this)); } endMethod(values){ console.log(values + this.prroperty); // 输出 "messageyes" } }
方案3:在构造函数中提前绑定方法
如果endMethod会被多次作为回调传递,建议在foo的构造函数里提前完成绑定,这样后续使用时无需重复绑定,代码更简洁:
class foo{ constructor(){ this.prroperty = 'yes'; // 构造阶段就把endMethod的this绑定到当前实例 this.endMethod = this.endMethod.bind(this); } eventMethod(){ let eventForm = new bar(); eventForm.fire(this.endMethod); } endMethod(values){ console.log(values + this.prroperty); // 输出 "messageyes" } }
这三种方案都不会影响类的复用性:你可以创建任意多个foo实例,每个实例的this都会正确指向自身;bar类也可以被所有foo实例共享调用,完美匹配你用foo做控制器、bar做弹出菜单的设计思路。
内容的提问来源于stack exchange,提问作者Vincent De Jong
相关产品推荐
相关产品推荐

