[英]How to call a method inside another method in a class in Javascript?
如何在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放在構造函數中並使其靜態。 該類應該是searchbar類的實用程序類。 如何做到這一點,以便可以在loadXMLDoc中調用processXMLReq。 因為在我的搜索欄類中,我只想做這樣的事情:
componentDidMount(){
// let xmlLoader = new XMLLoader();
let xmlLoader = new XMLLoader();
xmlLoader.loadXMLDoc('someURL', this.processXMLReq);
}
靜態方法不能用'this'訪問,它們是從構造函數或類名訪問的:
XMLLoader.processXMLReq(data);
要么
XMLLoader.constructor.processXMLReq(data);
XMLLoader。 processXMLreq(xhttp),因為它是靜態方法
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.