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

CpTw

在此代码块中:

  1. 如果我resolve / rejectconst关键字声明

    我需要将它们传递给executor不带的函数this,使用this会出错;

  2. 如果我resolve / rejectthis关键字声明

    我需要将它们传递给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] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章