Reputation: 63
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);
}
Upvotes: 0
Views: 415
Reputation: 36319
Static methods aren't accessed with 'this' they are accessed from the constructor or the classname:
XMLLoader.processXMLReq(data);
or
XMLLoader.constructor.processXMLReq(data);
Upvotes: 2