0

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?

  • 1
    metaData vs metadata? – BlakeH Jun 22 '16 at 20:15
  • Omg, nice catch! Although, I wrote the console.log() afterwards, to simplify the method for testing and rechecked now, with the corrected typo. It still doesn't work, with the same problem (metaData, properly spelled is still undefined) – Jovan Damjanovic Jun 22 '16 at 20:17
  • my last guess: you need to make sure the xhr has completed first, until then the property will be undefined. – BlakeH Jun 22 '16 at 20:30
  • you could test the above theory by setting the value for this.metaData to some temporary value prior to the xhr call – BlakeH Jun 22 '16 at 20:32
  • `.metaData` is just a standard object property, not sure why you refer to it as a "*private field*". There is no such thing in JS. – Bergi Jun 22 '16 at 21:45
  • See the duplicate for the *Why*. When you solve this (using promises!), notice that [it's a bad idea to do asynchronous things inside constructors](http://stackoverflow.com/q/24398699/1048572) anyway. – Bergi Jun 22 '16 at 21:47

0 Answers0