手写promise构造器的出错
来源:8-20 手写 Promise-then 的链式调用

慕丝1117639
2022-03-02
老师我想问一下为什么我这么写promise的构造器时,为什么resolve方法内部的this为undefined
class MyPromise{
state = 'pending'
value = null
reason = null
rejectCallbacks = []
resolveCallbacks = []
constructor(excutor){
try{
excutor(this.resolve,this.reject)
}catch(error){
this.reject(error)
}
}
resolve(value){
console.log('resolve:',this) //undefined
if(this.state ==='pending'){
this.value = value
this.state = 'resolved'
while(this.resolveCallbacks.length){
this.resolveCallbacks.shift()(this.value)
}
}
}
但是下面这样写的话,方法中的this就是实例对象
class person{
constructor(){
this.name = 'ohh'
}
say(){
console.log(this.name) //this为实例对象
}
}
请问为什么同样是在类方法中使用this,但是一个是undefined,一个是实例对象?
写回答
3回答
-
双越
2022-03-04
其实就一点:class 函数在被外部调用时,this 是 undefined 。例如
00 -
双越
2022-03-03
你是把 this.resolve 传递给了 excutor 函数去执行。这样 resolve 内部的 this 就不是 class 实例了。
这就例如
const obj { fn() { console.log(this) } } const fn1 = obj.fn fn1()
00 -
双越
2022-03-03
你是怎么调用的 resolve 函数?我看着代码没啥问题
042022-03-03
相似问题