【发布时间】:2011-06-08 23:21:29
【问题描述】:
我正在加载一个 csv 文件并对其进行解析。我希望得到的数组是某个对象的成员,但它最终是未定义的,因为我没有正确使用“this”关键字。
function SimPlayer(){
this.dataset = new Array();
var client = new XMLHttpRequest();
var dset = this.dataset;
function handler(){
if(client.readyState == 4){
if(client.status == 200){
//file is done loading
//split by lines
dset = client.responseText.split("\n");
for(var i=0; i<dset.length; i++){
//split each line by commas
dset[i] = dset[i].split(",");
//convert to ints
for(var j=0; j<dset[i].length; j++){
dset[i][j] = parseInt(dset[i][j]);
}
}
//dset is defined here, no problem. It contains the data from the csv file
console.log(dset[0]);
}
}
}
client.onreadystatechange = handler;
client.open("GET", "http://nathannifong.com/LayerCake/simdata/rec0_i0.csv");
client.send();
this.check = function(){
//does not work because this.dataset will be empty.
console.log(this.dataset[0])
}
}
假设我创建了一个 SimPlayer 实例,然后稍后调用 check(在 csv 文件有时间加载之后)
foo = new SimPlayer();
//....time passes....
foo.check();
foo.check() 原因
Uncaught TypeError: Cannot read property '0' of undefined
如何修复我的代码,以便在 check() 中,this.dataset 将包含 csv 文件中的数据?
【问题讨论】:
-
您在代码中的哪个位置为实际的
dataset数组设置了任何内容? -
另外,您可能会发现my answer to another question about prototypes 很有用。
-
为什么不在加载时将 dset 分配给 this.dataset,而不是之前?
-
如果我在 handler() 中引用 this.dataset,它不存在,因为在处理程序中,this 是指客户端
-
foo = new SimPlayer();后面不能跟foo.check(),因为你需要一些时间来做 AJAX,A 代表“异步”。
标签: javascript scope closures this