[英]jquery ajax and this, where to apply bind
我对“ this”的正确用法有疑问
我有一个名为Smartphone的类,它是一种从API获取JSONP数据的辅助方法,以及一种用于处理请求的数据等的访存方法。 这是我课堂上提到的部分:
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中的回调,成功和其他一些事情(例如反复试验)上使用bind。
编辑:我忘了提到确切的问题:我想要this._contacts是类的属性,获取数据后,我不能在其他方法中使用此。
编辑2:添加了fetchData调用示例。
我也已经阅读了apply / call / bind之间的区别,但无法弄清楚如何正确使用它。 来自Java的Java脚本使我很困惑,因此我将不胜感激。
感谢您的关注。
在这里看看: 如何在回调中访问正确的`this`?
而且,如果您想在响应中调用回调,则必须添加方括号
if (response.status === "ok") {
this._contacts = response.data;
// console.log(this._contacts);
callback();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.