I attempted to load a JSON file within a JavaScript class, but encountered an issue where the loaded data was only accessible inside a specific function.
class CreatePage {
constructor() {
var request = new XMLHttpRequest();
request.open('GET', 'data.json');
request.responseType = 'json';
request.send();
request.onload = function() {
this.data = request.response;
alert(this.data[1].Name); // This works
}
}
test(name) {
document.getElementById(name).innerHTML = this.data[1].Name;
}
}
const page = new CreatePage();
page.test("xyz"); // TypeError: this.data is undefined
Is there a way to store the loaded data as a class property?
EDIT: I appreciate the responses received so far. Despite trying solutions like `self=this`, `bind(this)`, and the arrow operator, I am still encountering the same TypeReference error.