简体   繁体   English

如何在Javascript类中的另一个方法内调用一个方法?

[英]How to call a method inside another method in a class in Javascript?

How do you properly call a method inside another method in a JavaScript class? 如何在JavaScript类中的另一个方法内正确调用一个方法?

export class XMLLoader{ 导出类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. 如您所见,我正在尝试在loadXMLDoc()中调用processXMLReq(),这为什么不起作用。 Only way I have made it to work is by putting processXMLReq inside the constructor and making it static. 我使之起作用的唯一方法是将processXMLReq放在构造函数中并使其静态。 This class is supposed to be a utility class for a searchbar class. 该类应该是searchbar类的实用程序类。 How can I make it so that I can call processXMLReq inside loadXMLDoc. 如何做到这一点,以便可以在loadXMLDoc中调用processXMLReq。 Because inside my searchbar class I just want to do something like this: 因为在我的搜索栏类中,我只想做这样的事情:

componentDidMount(){ componentDidMount(){

  //  let xmlLoader = new XMLLoader();

    let xmlLoader = new XMLLoader();

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


}

Static methods aren't accessed with 'this' they are accessed from the constructor or the classname: 静态方法不能用'this'访问,它们是从构造函数或类名访问的:

XMLLoader.processXMLReq(data);

or 要么

XMLLoader.constructor.processXMLReq(data);

XMLLoader. XMLLoader。 processXMLreq(xhttp) because it is a static method processXMLreq(xhttp),因为它是静态方法

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM