var mapFile = new XMLHttpRequest();
mapFile.open("GET", "http://localhost:8000/res/map01.txt", true);
mapFile.onreadystatechange = function() {
if (mapFile.readyState === 4) {
if (mapFile.status === 200) {
this.lines = mapFile.responseText.split("\n");
}
}
}
this.lines = mapFile.onreadystatechange.lines;
mapFile.send(null);
我有该代码,我正在尝试将this.lines
保存在mapFile.onreadstatechange
内,以便稍后在外部范围内另存为this.lines
。但是,mapFile.onreadystatachange.lines
未定义,我无法保存该变量供以后使用。我甚至尝试使用element.innerHTML
这是一个肮脏的黑客,但它也没有用。
答案 0 :(得分:2)
这里有三个主要问题:
this
中的onreadystatechange
与函数外部的this
不同,因为函数中的this
由函数的确定方式决定调用。更多关于我的博客:Mythical methods | You must remember this
XHR调用异步(默认情况下),因此当您尝试在{{1}上方使用this.lines
时,您的回调系统尚未被调用调用。 (即使有同步请求,因为该行 send
之前,它仍然不会被设置。)
send
在mapFile.onreadystatechange.lines
引用的函数对象上查找名为lines
的属性。它与在函数中定义的任何变量完全无关。
这是针对主要项目的更新:
mapFile.onreadystatechange