【问题标题】:Passing 'this' object to the 'then' callback function of $http service将“this”对象传递给 $http 服务的“then”回调函数
【发布时间】: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(){..." 可以在我的代码中看到。有什么帮助吗???

【问题讨论】:

  • 您的问题是.callthis 绑定到then,而不是绑定到作为参数传递给then 的函数。什么会起作用是.then(function(){ this.saved = true; }.bind(this);
  • @DRobinson 可能会这样回答吗?

标签: javascript angularjs callback


【解决方案1】:

为此分配一个 var 并改用该 var。见下文

var Product = function(){
    var self = this;
    self.name = "putty";
    self.price = 760;
    $http.post(url, data).then(function(response){
        self.saved = true;
    });
};

【讨论】:

    【解决方案2】:

    你需要重新分配它:

    var Product = function(){
        this.name = "putty";
        this.price = 760,
        self = this;
        $http.post(url, data).then.call(this, function(){
            self.saved = true;
        });
    };
    

    【讨论】:

    • @PSL 删除它,忘记从原始代码示例中删除它
    • 你们三个完全没有抓住重点。他使用.call 是有原因的。他的困惑是为什么.call 似乎没有使用他预期的正确this 调用该函数。混乱源于call被用于错误的函数(它正确设置this,但这样做是为了then函数,而不是他的回调。
    【解决方案3】:

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

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

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

    【讨论】:

    • this不会有回调函数的作用域吧?而不是Product 对象?
    • 不,绑定将创建该回调函数的副本,其中这是产品。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-10
    • 2019-04-13
    • 1970-01-01
    相关资源
    最近更新 更多