javascript,promises,如何在 then 范围内访问变量 this

javascript, promises, how to access variable this inside a then scope

我希望能够在 .then 范围内调用函数,为此我使用 this.foo() 方式。但是,如果我在 .then 中执行此操作,则会出现错误,因为 this 似乎丢失了。我能做什么?

在此代码中,这等同于对对象具有相同的输出 this

console.log(this)
one().then(function() {
  console.log(this)
})

function one() {
  var deferred = $q.defer();
  deferred.resolve()
  return deferred.promise;
}

这两个似乎都不起作用

console.log(this)
var a = this;
one().then(function(a) {
  console.log(a)
})

你的第二个代码示例是正确的方法。因为新函数的作用域改变了,this 也改变了,所以你在函数外引用 this 是正确的。

它失败的原因是因为该函数正在使用您传递给函数的 a 而不是您在其外部定义的全局 a

换句话说:

var a = this;

one().then(function () {
  console.log(a)
});

更新:使用箭头函数 - 他们从外部范围借用上下文 (this)。

function two() {
  console.log('Done');
}

one().then(() => {
  this.two();
});

function one() {
  return new Promise(res => {
    setTimeout(() => res(), 2000);
  });
}