手写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 。例如

//img.mukewang.com/szimg/62215b5c0916053e07260336.jpg

0
0

双越

2022-03-03

你是把 this.resolve 传递给了 excutor 函数去执行。这样 resolve 内部的 this 就不是 class 实例了。

这就例如

const obj {
    fn() {
        console.log(this)
    }
}
const fn1 = obj.fn
fn1()


0
0

双越

2022-03-03

你是怎么调用的 resolve 函数?我看着代码没啥问题

0
4
慕丝1117639
回复
双越
老师,请问在初始化的Promise对象的时候,调用resolve方法属于哪一种调用方式呀? 如果是当成普通函数调用,应该是window才对 但是如果当成对象的方法,那不就是this吗? 还有会不会和严格模式有关?但是我代码中没有声明使用严格模式,应该不会是严格模式造成的吧
2022-03-03
共4条回复

一天时间高效准备前端技术一面 匹配大厂面试要求

针对时下面试高频考点,帮助新人js面试快速通关

4694 学习 · 1681 问题

查看课程