I am working on a project in ES6 and as part of it I am developing a class that needs to load some data from a file and then parse and work on it. The basic structure of my class is as follows:
class FactoryClass {
constructor(catalogueName, metaDataDoc) {
this.catalogueName = catalogueName;
var that = this;
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (xhttp.readyState == 4 && xhttp.status == 200) {
that.metaData = xmlToJson(xhttp.responseXML);
}
};
xhttp.open("GET", metaDataDoc, true);
xhttp.send();
}
newProduct(type) {
console.log(this.metaData);
}
}
var factory = new FactoryClass('default', 'data/Components.xml');
var component = factory.newProduct('Irrelevant');
Upon running this code, the console logs 'undefined'. Running factory.metaData in the console I see that the data is loaded and parsed properly but the newProduct method cannot 'see' it.
In the same file I have this code as well:
class Part {
constructor(id, name) {
this.id = id;
this.name = name;
}
render() {
return this.name;
}
}
var testPart = Part(0, 'somePart');
console.log(testPart.render());
Running that displays 'somePart' as expected.
How is it that one class can access the internal members and the other can't? The only difference that springs to mind is the AJAX request and I am not really satisfied with the way I handled loading that data from a file so if that is the problem can anyone tell me how could I fix this in a satisfying manner?