深刻理解:为什么 .bind(this) 与 new Promise 一起使用时似乎不遵循正常规则

Deep understanding: Why do .bind(this) not seem to follow the normal rules when used with new Promise

以下代码:

var this_module = {

    foo: 'something',

    promise: function () {

        return new Promise (function(resolve, reject) {

            resolve (this.foo);
        }.bind(this))
    }
}

成功将 this 绑定到 this_module。我不明白为什么。

new 运算符通常将 this 设置为作为对给定函数的构造调用的一部分创建的对象。这应该意味着对 Promise 函数的构造调用会将 this 设置为 Promise 对象。如果是这种情况,那么 .bind(this) 也应该将执行函数的 this 设置为 Promise 对象。

或者 .bind(this) 应该将执行函数的 this 设置为 Promise 函数(在上面的例子中应该是全局对象)的 this 值。

为什么不是这样?

var this_module = {

  foo: 'something',

  promise: function () {
    return new Promise(function(resolve, reject) {
      resolve(this.foo);
    }.bind(this));
  }

};

适用 this 的一般规则。 bind(this) 中的 this 出现在 this_module 的方法 promise 中,因此根据定义指的是 this_module(假设它被称为 this_module.promise() ).因此,它所应用的函数中的 this(在本例中是执行程序——作为参数传递给 new Promise 的函数)引用 this_module,并且可以访问 foo。这里没有什么奇怪的事情发生。

正如评论中所解释的,this 执行者所绑定的,因此在执行者内部有效,与承诺无关,或与任何 this 相关新的承诺。事实上,您无法通过设计访问正在构建的承诺。任何引用新承诺的 this 都发生在 Promise 构造函数中,这对您是不可见的。

也许反对票是因为这段代码可以用 this 的正常规则很简单地解释,但它们看起来确实有点苛刻。

您可能会认为您所写的内容恰好等同于以下内容:

var this_module = {

  foo: 'something',

  promise: function () {
    const self = this;

    return new Promise(function(resolve, reject) {
      resolve(self.foo);
    });
  }

};

也等同于

var this_module = {

  foo: 'something',

  promise: function () {
    return new Promise((resolve, reject) =>
      resolve(this.foo);
    );
  }

};