我在将“this”对象传递给 $http 服务的“then”回调函数时遇到问题,如下所示
var Product = function(){
this.name = "putty";
this.price = 760;
$http.post(url, data).then.call(this, function(){
this.saved = true;
});
};
当我检查语句 this.saved = true 中的“this”对象时,我意识到它指向全局对象而不是预期的 Product 实例,因为我有“then.call(this, function( ){..."而不是在我的代码中可以看到的 "then(this, function(){..."。有什么帮助吗???
最佳答案
当使用 then.call(this, function(){});
时,您正在调用 then
函数作为 this
,但是这不会影响您传递的实际回调函数的 this
值。
如果你想绑定(bind)this
到回调,你可以使用bind
:
$http.post(url, data).then(function(){
this.saved = true;
}.bind(this));
关于javascript - 将 'this'对象传递给$http服务的 'then'回调函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30268550/