javascript,promises,如何在当时范围内访问变量 [英] javascript, promises, how to access variable this inside a then scope

查看:173
本文介绍了javascript,promises,如何在当时范围内访问变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

In this code, this would be equivalent to have the same output for the object 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)
})


推荐答案

你的第二个代码示例是正确的方法。由于新功能的范围发生了变化,也会发生变化,因此您可以引用这个在函数之外。

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

它失败的原因是因为函数使用了你传递给函数的 a 而不是你在它之外定义的全局 a

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

换句话说:

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

这篇关于javascript,promises,如何在当时范围内访问变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆