在ajax中访问父对象的`this`变量

时间:2018-04-30 12:29:04

标签: javascript asynchronous

我理解Ajax是异步的,但我仍然无法理解对象作用域以及javascript如何使用this的方式如何工作。

mylibrary = { 
        my_variable: 0,
        my_function: function() {
                $.ajax({
                        url: "/theinternet",
                        method: "POST",
                        data: {
                                // things
                        },   
                        success: function(response) {
                                this.my_variable += 1; // How do I access my_variable?
                                console.log("HOORAY!");
                        },   
                        error: function(error) {
                                console.log("ERROR");
                        }    
                // }).bind(this); this doesn't work.
                }).bind(this);
        }   
}

我想如何在ajax调用的成功函数中访问my_variable

这似乎是人们需要做的非常普遍的事情,不是吗?

4 个答案:

答案 0 :(得分:2)

使用对象名称。更改this.my_variable += 1;

mylibrary.my_variable += 1;

答案 1 :(得分:2)

<强>解决方案my_function: function()更改为箭头函数() =>语法可以解决问题。

<强>背景 问题是传递给ajax调用的this值来自my_function而不是my_library对象。这是因为function始终使用自己的this范围,您可以使用不会产生新this的箭头函数。

答案 2 :(得分:1)

您可以在ajax请求之外的变量中分配this的引用,以便可以在ajax请求中访问该变量。像这样的东西,

mylibrary = {
    my_variable: 0,
    my_function: function() {
      var _this = this;
      $.ajax({
        url: "/theinternet",
        method: "POST",
        data: {
          // things
        },
        success: function(response) {
          _this.my_variable += 1; // How do I access my_variable?
          console.log("HOORAY!");
        },
        error: function(error) {
          console.log("ERROR");
        }
      });
    }
  }

在此代码中,我们var _this = this;可以在_this内访问$.ajax,因为ajax请求位于my_function,而_this位于my_function的本地范围内引用this的{​​{1}}。现在,当您使用_this.my_variable时,它将更改对象my_variable的{​​{1}}

您的代码中的错误是您没有使用该函数绑定mylibrary。您应该这样做以获得this工作

bind

答案 3 :(得分:0)

您可以使用let _this = this将父方法的范围指定给变量,并在内部函数中使用它。

 mylibrary = { 
            my_variable: 0,
            my_function: function() {
                    let _this = this;
                    $.ajax({
                            url: "/theinternet",
                            method: "POST",
                            data: {
                                    // things
                            },   
                            success: function(response) {
                                    _this.my_variable += 1; // How do I access my_variable?
                                    console.log("HOORAY!");
                            },   
                            error: function(error) {
                                    console.log("ERROR");
                            }    
                    // }).bind(this); this doesn't work.
                    }).bind(this);
            }   
    }
相关问题