【问题标题】:jquery ajax and this, where to apply bindjquery ajax 和 this,在哪里应用绑定
【发布时间】:2018-08-21 19:38:04
【问题描述】:

我对“this”的正确用法有疑问
我有一个名为 Smartphone 的类,一个从 API 获取 JSONP 数据的辅助方法和一个 fetch 方法来处理请求的数据等。这是我课堂上提到的部分:

class Smartphone {

fetchData(data, callback) {

    switch (data.action) {
        case "contacts":
            this.getJSONP(data, function (response) {
                if (response.status === "ok") {
                    this._contacts = response.data;
                   // console.log(this._contacts);
                    callback;
                }
            });

            break;
    }

}
 render(tab) {

    this.fetchData({"action": "contacts"}, function () {
    // code will be inserted later, tab unused in this example
    });
    console.log(this._contacts);

}

getJSONP(data, callback) {
    return $.ajax({
        context: this,
        url: 'URL',
        dataType: 'jsonp',
        data: data,
        success: callback
    });
}

}

我尝试在 this.getJSONP 中的回调上使用绑定,成功和其他一些事情(à la 试验和错误)。

编辑:我忘了提到确切的问题:我希望 this._contacts 成为类的属性,在获取数据后我不能在其他方法中使用它。

编辑 2:添加了 fetchData 调用的示例。

我也阅读了 apply/call/bind 之间的区别,但不知道如何正确使用它。来自 Java 的 Javascript 让我很困惑,所以我非常感谢您的解释。
感谢您的关注。

【问题讨论】:

  • 使用 response => { 代替 function(response){function 创建一个新范围并更改其中的 this。 Arow 函数不会改变 this 所以它仍然是回调中的类。
  • 如何调用fetchData?
  • 你也可以function (response) { ... }.bind(this);
  • 我尝试了箭头函数和函数(响应){ ... }.bind(this);,还添加了一个fetchData示例,我的脚本总是返回未定义的_contacts

标签: jquery ajax class this bind


【解决方案1】:

看看这里:How to access the correct `this` inside a callback?

如果你想在响应中调用回调,你必须添加括号

 if (response.status === "ok") {
          this._contacts = response.data;
          // console.log(this._contacts);
          callback();
 }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-12-20
    • 1970-01-01
    • 1970-01-01
    • 2020-01-15
    • 2023-02-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多