我希望能够调用 然后 范围,为此我使用 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) });
更新:使用箭头函数-它们借用上下文( 这 )从他们的外部范围。
function two() { console.log('Done'); } one().then(() => { this.two(); }); function one() { return new Promise(res => { setTimeout(() => res(), 2000); }); }