Javascript,承诺,如何在then范围内访问变量this

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

本文关键字:范围内 访问 this then 变量 承诺 Javascript      更新时间:2023-09-26

我希望能够在内部调用函数。然后作用域,为此我使用this.foo()方式。但是如果我在里面这么做。然后我得到一个错误,因为这个似乎丢失了。我能做什么?

在这段代码中,这相当于对对象有相同的输出

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);
  });
}