0
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.innerHTMLwhich 是一个肮脏的黑客,但它也没有用。

4

1 回答 1

2

这里有三个主要问题:

  1. 内部与函数外部不同,因为函数this内部取决于函数的调用方式。更多关于我的博客:神话方法| 你必须记住onreadystatechangethisthisthis

  2. XHR 调用是异步的(默认情况下),因此当您尝试在调用this.lines上方使用时,您的回调不会被send调用。(即使是同步请求,由于该行是before send,它仍然不会被设置。)

  3. mapFile.onreadystatechange.lines查找在 .lines引用的函数对象上调用的属性mapFile.onreadystatechange。它与该函数中定义任何变量完全无关。

以下是针对主要项目的更新:

var mapFile = new XMLHttpRequest();
var self = this; // <===== Remember `this` for use in the callback
mapFile.open("GET", "http://localhost:8000/res/map01.txt", true);

mapFile.onreadystatechange = function() {
  if (mapFile.readyState === 4) {
    if (mapFile.status === 200) {
      // v---- Use self instead of this
      self.lines = mapFile.responseText.split("\n");
    }
  }
}; // <=== Add missing semicolon

// Removed a line here using `this.lines` prematurely

mapFile.send(null);
于 2013-02-02T12:09:10.147 回答