我对'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之间的区别,但无法弄清楚如何正确使用它。 Javascript对我来说非常困惑,所以我非常感谢你的解释 谢谢你的关注。
答案 0 :(得分:0)
看看这里:How to access the correct `this` inside a callback?
如果你想在你的回复中调用回调,你必须添加括号
if (response.status === "ok") {
this._contacts = response.data;
// console.log(this._contacts);
callback();
}