gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 02:59:51 25 4
gpt4 key购买 nike

如何正确调用 JavaScript 类中另一个方法中的方法?

导出类 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();

}

};

正如您所看到的,我正在尝试在 loadXMLDoc() 内调用 processXMLReq(),为什么这不起作用。我让它工作的唯一方法是将 processXMLReq 放入构造函数中并使其静态。这个类应该是搜索栏类的实用程序类。我怎样才能做到这一点,以便我可以在 loadXMLDoc 中调用 processXMLReq。因为在我的搜索栏类中我只想做这样的事情:

componentDidMount(){

  //  let xmlLoader = new XMLLoader();

let xmlLoader = new XMLLoader();

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


}

最佳答案

Static methods aren't accessed with 'this'它们可以从构造函数或类名访问:

XMLLoader.processXMLReq(data);

XMLLoader.constructor.processXMLReq(data);

关于javascript - 如何在Javascript中调用类中另一个方法中的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46504508/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com