Javascript 解析角度承诺时保持对调用对象的引用 问题
在解析承诺时,javascript上下文会更改为Window,这意味着我不能引用解析承诺的对象,也不能使用或更改其任何变量 如果我使用一个that=this hack,我可以引用它,但问题是如果我有多个对象使用这个hack,它们将共享同一个窗口。这个变量,它们将混淆 下面是我为演示此问题而创建的一些示例代码: app.js index.html 在解析承诺时,如何跟踪对象的位置 试试var=this;否则,您将使用一个一直被覆盖的全局变量-或者查看绑定-例如Javascript 解析角度承诺时保持对调用对象的引用 问题,javascript,angularjs,angular-promise,Javascript,Angularjs,Angular Promise,在解析承诺时,javascript上下文会更改为Window,这意味着我不能引用解析承诺的对象,也不能使用或更改其任何变量 如果我使用一个that=this hack,我可以引用它,但问题是如果我有多个对象使用这个hack,它们将共享同一个窗口。这个变量,它们将混淆 下面是我为演示此问题而创建的一些示例代码: app.js index.html 在解析承诺时,如何跟踪对象的位置 试试var=this;否则,您将使用一个一直被覆盖的全局变量-或者查看绑定-例如 this.oddCheck = fu
this.oddCheck = function(i){
var promise = MyService.evenOrOdd(i);
promise.then(function(value){
console.log(this.rand + "|" + value);
}.bind(this));
promise.catch(function(value){
console.log(this.rand + "|" + value);
}.bind(this));
};
最后,上述函数也可以写成:
this.oddCheck = function(i){
MyService.evenOrOdd(i)
.then(function(value){
console.log(this.rand + "|" + value);
}.bind(this))
.catch(function(value){
console.log(this.rand + "|" + value);
}.bind(this));
};
我喜欢用这种方式。您应该返回对象。您可以在该对象内引用自身。例如: 还可以使用Ecmascript 6箭头函数。它提供父上下文..thenres=>console.logthis.rand//这将是一个outter函数
creating new factory object with rand = 0.10776704256566871
app.js (line 38)
creating new factory object with rand = 0.5952598424233105
app.js (line 38)
even or odd for: 10
app.js (line 8)
even or odd for: 11
app.js (line 8)
starting time out
app.js (line 12)
0.5952598424233105|Even10 //Rand is wrong
app.js (line 46)
starting time out
app.js (line 12)
0.5952598424233105|Odd:11
app.js (line 46)
this.oddCheck = function(i){
var promise = MyService.evenOrOdd(i);
promise.then(function(value){
console.log(this.rand + "|" + value);
}.bind(this));
promise.catch(function(value){
console.log(this.rand + "|" + value);
}.bind(this));
};
this.oddCheck = function(i){
MyService.evenOrOdd(i)
.then(function(value){
console.log(this.rand + "|" + value);
}.bind(this))
.catch(function(value){
console.log(this.rand + "|" + value);
}.bind(this));
};