【问题标题】:javascript, promises, how to access variable this inside a then scope [duplicate]javascript,promise,如何在 then 范围内访问变量 this [重复]
【发布时间】:2015-12-09 10:44:16
【问题描述】:

我希望能够在 .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)
})

【问题讨论】:

  • 如果您从one().then(function(a) { 中删除a 参数,使其成为one().then(function() {,那么这将为您提供您想要的结果。
  • 是的,当我看到你的答案时,我正在测试它。你完全正确!如果您将其发布为答案,我会将其标记为答案

标签: javascript promise angular-promise


【解决方案1】:

您的第二个代码示例是正确的方法。因为新函数的作用域发生了变化,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);
  });
}

【讨论】:

  • 或 ...one().then(function () { console.log(this) }.bind(this)) 通常的免责声明,9 之前的 internet explorer 是浪费磁盘空间,除了显示静态网页之外,不应依赖它来做任何事情
  • 是的,@JaromandaX,我只是在查看某人对答案所做的编辑,但代码看起来不正确。你的看起来很准确。
  • 你的是对的,而且在很多情况下可能更容易使用,你只要看看你把 var a = this 放在哪里就知道 a/this 到底是什么 - 而使用绑定,它可能并不完全正确您对此的期望或想要什么:p
  • 非常感谢你的好榜样。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-08-06
  • 2013-06-12
  • 2016-10-29
  • 1970-01-01
  • 1970-01-01
  • 2018-06-12
  • 1970-01-01
相关资源
最近更新 更多