javascript - 为什么 'this' 在使用 Promise 时在类方法内部未定义?

标签 javascript node.js promise this q

我有一个 javascript 类,每个方法都返回一个 Q promise 。我想知道为什么 thismethod2method3 中未定义。有没有更正确的方法来编写这段代码?

function MyClass(opts){
  this.options = opts;

  return this.method1()
    .then(this.method2)
    .then(this.method3);
}

MyClass.prototype.method1 = function(){
  // ...q stuff...

  console.log(this.options); // logs "opts" object

  return deferred.promise;
};

MyClass.prototype.method2 = function(method1resolve){
  // ...q stuff...

  console.log(this); // logs undefined

  return deferred.promise;
};

MyClass.prototype.method3 = function(method2resolve){
  // ...q stuff...

  console.log(this); // logs undefined

  return deferred.promise;
};

我可以使用 bind 来解决这个问题:

function MyClass(opts){
  this.options = opts;

  return this.method1()
    .then(this.method2.bind(this))
    .then(this.method3.bind(this));
}

但不完全确定为什么需要 bind.then() 会杀死 this 吗?

最佳答案

this 始终是调用该方法的对象。但是,当将方法传递给 then() 时,您并没有调用它!该方法将存储在某个地方并稍后从那里调用。如果你想保留 this,你必须这样做:

.then(() => this.method2())

或者如果你必须以 ES6 之前的方式来做,你需要在之前保留 this:

var that = this;
// ...
.then(function() { that.method2() })

关于javascript - 为什么 'this' 在使用 Promise 时在类方法内部未定义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34930771/

相关文章:

javascript - Jquery 无法调用未定义的方法替换

javascript - 如何评估数组中每个项目包含 settimeout 的函数 (Javascript)

JavaScript 全局变量声明语法

angularjs - Satellizer 和推特登录

node.js - Alexa 在数据返回之前做出响应

reactjs - 使用 useEffect() Hook 和 Async/Await 从 Firebase/Firestore 获取数据

javascript - 如何在knockout-postbox.js中预选Section以使内容可见

javascript - 将其名称位于变量中的 View 文件包含到 EJS 模板中

javascript - 如何从 fs.readfile 回调函数中获取数据

javascript - 当数组中的所有项目都已处理完毕后调用done()