为什么构造函数中的这个函数引用对象实例,即使它不是属性?

问题描述 投票:0回答:1
function Promise (callback){

    //this = {}
    //because of "new" keyword, an empty object is automatically created, and the "this" is referencing to that object.
    
   this.status = "pending";

   const resolve = () => {
            this.status = "fulfilled";
            console.log("status is: " + this.status      
    };
  
    callback(resolve);
    
    //return this 
    // at the end, javascript automatically returns the "this" object.
}

console.log("start")

const p1 = new Promise((resolve) => {
    setTimeout(() => resolve(), 3000);
});

setTimeout(() => console.log(p1.status), 4000)

//output:
 //start
 //status is: fulfilled
 //fulfilled

现在,p1 是 Promise 的对象实例。

this
”对象返回给p1变量后,
resolve
函数尚未执行,3秒后才执行。

resolve
函数不是对象的属性或方法,因为它没有写成 this.resolve(){...} 或 Promise.prototype.resolve()....

我的问题是:当

resolve
函数在回调中传递:
callback(resolve)
时,resolved函数中的“
this
”正在引用新创建的对象
this = {}
不是 p1 对象?

但是当调用

resolve
函数时,它会改变p1的状态。所以它的
this
实际上引用了 p1 对象。这是为什么?我很困惑。

...即使我这样做:

this.resolve = () => {
            this.status = "fulfilled";
            console.log("status is: " + this.status      
    };
  
callback(this.resolve);

this.resolve中的

this
仍将引用新创建的对象:据我所知,
this = {}

上面的代码来自:https://medium.com/swlh/implement-a-simple-promise-in-javascript

我刚刚修改过。

javascript promise
1个回答
0
投票

resolve()
的箭头函数声明捕获函数声明处
this
的词法值。因为
this
的词法值是构造函数内的
this
,所以它自然会指向由该构造函数创建的新创建的对象。

this
的词法值被硬连接到
resolve
的特定声明中(这就是箭头函数的工作原理)。

注意,Promise 构造函数的每个实例都会创建一个新的解析函数副本,并绑定了不同的词法

this

这是箭头函数的一个非常重要的特性,如果你这样做

function resolve() {}
就不会出现这种情况。

© www.soinside.com 2019 - 2024. All rights reserved.