手写 promise 代码中,关于作用域执行上下文的问题求解?
看网上手写promise,看到这个部分就看不懂了
    class MyPromise{        constructor(func){
            this.state = 'PENDING';
            console.log(this.state,'11')
            func(this.resolve.bind(this))
        }
        resolve(){
            this.state = 'REJECTED'
        }
        then(){
            return new MyPromise(res=>{
                console.log(this.state,'22')
            })
        }
    }
    new MyPromise(res=>{
        res()
    }).then()
打印:
为什么state赋值了PENDING,回调里state=REJECTED
回答:
看图


回答:
箭头函数没有自己的 this 。它里面的 this 是包含它的函数的 this 。包含它的函数时 then 。于是里面的 this 并不是你新创建的 promise ,而是原来那一个。
        then(){ // <--- this 是这里的 this            return new MyPromise(res=>{
                console.log(this.state,'22')
            })
        }
以上是 手写 promise 代码中,关于作用域执行上下文的问题求解? 的全部内容, 来源链接: utcz.com/p/937562.html
