将'this'对象传递给$ http服务的'then'回调函数 [英] Passing 'this' object to the 'then' callback function of $http service

查看:586
本文介绍了将'this'对象传递给$ http服务的'then'回调函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在将'this'对象传递给$ http服务的'then'回调函数时遇到问题,如下所示

I am having problems passing 'this' object to the 'then' callback function of $http service as shown below

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(){...

When I inspect 'this' object in the statement this.saved = true, I realise that it is pointing to the global object and not to an instance of Product as expected since I have "then.call(this, function(){..." instead of "then(this, function(){..." as can be seen in my code. Any help please???

推荐答案

在使用 then.call(this, function(){}); ,您正在调用 then 函数作为 this ,但这不会影响您传递的实际回调函数的 this 值。

When using then.call(this, function(){}); you're calling the then function as this, but that will not affect the this value of the actual callback function that you are passing.

如果要将 this 绑定到回调,可以使用 bind

If you want to bind this to the callback, you can use bind:

$http.post(url, data).then(function(){
    this.saved = true;
}.bind(this));

这篇关于将'this'对象传递给$ http服务的'then'回调函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆