【发布时间】:2015-07-27 21:53:33
【问题描述】:
我在将“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(){..." 可以在我的代码中看到。有什么帮助吗???
【问题讨论】:
-
您的问题是
.call将this绑定到then,而不是绑定到作为参数传递给then的函数。什么会起作用是.then(function(){ this.saved = true; }.bind(this); -
@DRobinson 可能会这样回答吗?
标签: javascript angularjs callback