如何在Javascript构造函数传递参数?



在此代码块中:

  1. 如果我用const关键字声明resolve / reject

    我需要将它们传递给executor函数而不传递给this,使用this会得到错误;

  2. 如果我用this关键字声明resolve / reject

    我需要通过this将它们传递给executor函数。

是什么导致了这种不同的行为?

这两种方式有什么不同?

请帮帮我,谢谢~

class myPromise {
constructor(executor) {

this.status = PENDING;
this.value = null;
this.reason = null;
const resolve = value => {
this.value = value;
}
this.reject = reason => {
this.reason = reason;
}

// Why not use this.resolve / this.reject ?
// 
executor(resolve, this.reject);
}
then(onfulfilled = Function.prototype, onrejected = Function.prototype) {
onfulfilled(this.value);
onrejected(this.reason);
}
}

为什么不用这个呢?解决这个问题。拒绝吗?

this.resolve不能工作,因为resolve不是this的一部分。回想一下,用const声明的变量只能在声明它们的块中访问,在本例中是constructor { ... }(docs)。

另一方面,当你说this.reject时,你实际上是把这个值赋给this,每次你想再次引用这个值时,都必须使用this.

相关内容

最新更新