小编典典

为什么在使用诺言时在类方法中未定义“ this”?

node.js

我有一个javascript类,每个方法都返回一个QPromise。我想知道为什么thismethod2和中未定义method3。有没有更正确的方法来编写此代码?

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


阅读 285

收藏
2020-07-07

共1个答案

小编典典

this始终是调用方法的对象。但是,将方法传递给时then(),您不会调用它!该方法将存储在某个地方,稍后再从那里调用。如果要保存this,则必须这样做:

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

或者,如果您必须在ES6 this之前的版本中进行操作,则需要先保存以下内容:

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