Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/374.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 解析角度承诺时保持对调用对象的引用 问题_Javascript_Angularjs_Angular Promise - Fatal编程技术网

Javascript 解析角度承诺时保持对调用对象的引用 问题

Javascript 解析角度承诺时保持对调用对象的引用 问题,javascript,angularjs,angular-promise,Javascript,Angularjs,Angular Promise,在解析承诺时,javascript上下文会更改为Window,这意味着我不能引用解析承诺的对象,也不能使用或更改其任何变量 如果我使用一个that=this hack,我可以引用它,但问题是如果我有多个对象使用这个hack,它们将共享同一个窗口。这个变量,它们将混淆 下面是我为演示此问题而创建的一些示例代码: app.js index.html 在解析承诺时,如何跟踪对象的位置 试试var=this;否则,您将使用一个一直被覆盖的全局变量-或者查看绑定-例如 this.oddCheck = fu

在解析承诺时,javascript上下文会更改为Window,这意味着我不能引用解析承诺的对象,也不能使用或更改其任何变量

如果我使用一个that=this hack,我可以引用它,但问题是如果我有多个对象使用这个hack,它们将共享同一个窗口。这个变量,它们将混淆

下面是我为演示此问题而创建的一些示例代码:

app.js

index.html

在解析承诺时,如何跟踪对象的位置

试试var=this;否则,您将使用一个一直被覆盖的全局变量-或者查看绑定-例如

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