I have a problem with the correct usage of 'this'
I have a class called Smartphone, a helper-method to get JSONP data from an API and a fetch method to process the requested data and such. Here's the mentioned part of my Class:
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
});
}
}
I tried using bind on the callback in this.getJSONP, on success and a few other things (à la trial and error).
Edit: I forgot to mention the exact problem: I want this._contacts to be the property of the class, i cant use this one in other methods after fetching the data.
Edit 2: added a example for fetchData call.
I also have read the difference between apply/call/bind but can't figure it out how to use it properly. Javascript is pretty confusing to me coming from Java so I would appreciate an explanation very much.
Thanks for you attention.