自定义MyPromise类中resolve无法调用then方法的问题求助
问题分析与解决
核心原因:this指向丢失
当你把this.resolve作为参数传给构造函数的回调cb时,resolve函数的上下文(this)已经和MyPromise实例解绑。外部调用resolve(42)时,resolve内部的this不再指向MyPromise实例,导致this.then无法找到对应的方法。
修复方案
有两种常用的修复方式:
方式1:在构造函数中绑定this
通过bind方法将resolve和reject的this固定为MyPromise实例:
class MyPromise{ constructor(cb){ // 绑定this到resolve、reject,确保调用时上下文指向实例 this.resolve = this.resolve.bind(this); this.reject = this.reject.bind(this); cb(this.resolve, this.reject) } resolve(value){ this.then(value) } then(val){ console.log("here") return val; } reject(){ } } var p = new MyPromise((resolve, reject)=>{ resolve(42) });
方式2:用箭头函数定义方法
箭头函数会自动继承构造函数的this上下文,无需手动绑定:
class MyPromise{ constructor(cb){ cb(this.resolve, this.reject) } // 箭头函数自动绑定构造函数的this resolve = (value) => { this.then(value) } then(val){ console.log("here") return val; } reject = () => { } } var p = new MyPromise((resolve, reject)=>{ resolve(42) });
补充说明
你之前尝试的this.self = this无效,是因为resolve内部的this已经不是实例,this.self根本不存在。如果要沿用这种思路,需要在构造函数中将self注入到resolve的作用域,但显然上述两种绑定this的方式更简洁规范。
内容的提问来源于stack exchange,提问作者ABGR
相关产品推荐
相关产品推荐

