编程语言
首页 > 编程语言> > Javascript这个范围问题

Javascript这个范围问题

作者:互联网

我正在加载一个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文件的数据?

解决方法:

您将要存储对适当的此绑定的引用:

var _this = this;
this.check = function(){
    //does not work because this.dataset will be empty.
    console.log(_this.dataset[0])
}

标签:scope,closures,this,javascript
来源: https://codeday.me/bug/20191208/2094324.html