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

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

问题描述

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

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?

在这段代码中,这相当于对对象this

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

推荐答案

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

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,如何在 then 范围内访问变量 this的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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