gpt4 book ai didi

javascript - 将 'this'对象传递给$http服务的 'then'回调函数

转载 作者:行者123 更新时间:2023-11-29 16:58:17 25 4
gpt4 key购买 nike

我在将“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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com