在此代码块中:
如果我resolve / reject
用const
关键字声明,
我需要将它们传递给executor
不带的函数this
,使用this
会出错;
如果我resolve / reject
用this
关键字声明,
我需要将它们传递给executor
函数this
。
是什么原因导致这种不同的行为?
这两种方式之间有什么区别?
请帮帮我,谢谢〜
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 / this.reject?
this.resolve
将不起作用,因为resolve
它不属于this
。回想一下,用声明的变量const
只能在声明它们的块中访问,在这种情况下为constructor { ... }
(docs)。
另一方面,当您说this.reject
自己实际上是将该值分配给时this
,则this.
每次想再次引用该值时都必须使用。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句