0

How do you properly call a method inside another method in a JavaScript class?

export class XMLLoader{

constructor(){



}

// Processes the XML request, i.e retrieves the relevant data etc.
 processXMLReq(xhttp){

    let resultXML = xhttp.responseXML;
    let resultText = xhttp.responseText;


    console.log("The result is: " + resultXML);
    console.log("The result is: " + resultText);

    let x = resultXML.getElementsByTagName("road")[0].childNodes[0].nodeValue;


    console.log("The first 'road' node value is: " + x);

}

loadXMLDoc(url){

    let xhttp = new XMLHttpRequest();

    xhttp.onreadystatechange = function(){
        if(this.readyState === 4 && this.status === 200){
            this.processXMLReq(xhttp);
        }

    };

    xhttp.open("GET", url, true);       // the argument "true" means that the request will be executed in async
    xhttp.send();

}

};

As you can see I'm trying to call processXMLReq() inside loadXMLDoc(), why is this not working. Only way I have made it to work is by putting processXMLReq inside the constructor and making it static. This class is supposed to be a utility class for a searchbar class. How can I make it so that I can call processXMLReq inside loadXMLDoc. Because inside my searchbar class I just want to do something like this:

componentDidMount(){

  //  let xmlLoader = new XMLLoader();

    let xmlLoader = new XMLLoader();

    xmlLoader.loadXMLDoc('someURL', this.processXMLReq);


}

2 Answers 2

2

Static methods aren't accessed with 'this' they are accessed from the constructor or the classname:

XMLLoader.processXMLReq(data);

or

XMLLoader.constructor.processXMLReq(data);
Sign up to request clarification or add additional context in comments.

5 Comments

Ah, yes of course! But imagine processXMLReq wasn't static. How would you do it then? Because that is what I actually intended to ask, just forgot to remove the static in front. Sorry for the confusion.
If it's not static, then addressing it with this.processXMLReq() should work.
Actually, looking at your consuming code, are you asking how the consumer references it?
Yes, because without it being static, and then I get an error that processXMLReq is undefined, although it is an member method.
In loadXml(), you can reference this.processXML(), but outside of the class instance you cannot. You'd have to do xmlLoader.processXML().
0

XMLLoader. processXMLreq(xhttp) because it is a static method

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.