我有一个 javascript 类,每个方法都返回一个QPromise。我想知道为什么this在method2and 中未定义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?