I'm trying to load some JSON into a JavaScript class and assign some properties from the JSON to properties on an instance of the class, but I'm having trouble with 'this' and scope. I'm pretty sure the solution involves arrow functions, but I can't figure out how to piece things together.
Here's what I have so far:
class Test {
constructor(url) {
this.loadJSON(url, this.init);
}
loadJSON(url, callback) {
let xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.responseType = 'json';
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
callback(xhr.response);
}
};
xhr.send(null);
}
init(response) {
console.log(response.description);
// this is undefined
this.description = response.description;
}
}
In the init() method, the console.log works as I'd expect, but I'm having trouble assigning anything to the object - I just keep getting 'this is undefined.'