在此代码块中:
-
如果我用
const
关键字声明resolve / reject
,我需要将它们传递给
executor
函数而不传递给this
,使用this
会得到错误; -
如果我用
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.
。