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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32547735/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 10:35:27  来源:igfitidea点击:

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

javascriptpromiseangular-promise

提问by GWorking

I want to be able to call a function inside the .thenscope, and for that I use the this.foo()manner. But if I do this inside the .thenI get an error, since thisappears to be lost. What can I do?

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

In this code, this would be equivalent to have the same output for the object this

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

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

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

This neither seems to work

这似乎都不起作用

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

回答by Andy

Your second code example is the right way to go. Because the scope changes in the new function, thischanges too, so you're right to make a reference to thisoutside of the function.

您的第二个代码示例是正确的方法。因为作用域在新函数中this发生了变化,也会发生变化,所以您this对函数外部进行引用是正确的。

The reason it failed is because the function is using athat you passed into the function rather than the global ayou defined outside it.

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

In other words:

换句话说:

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