Javascript - 如何将原始对象传递给回调函数

时间:2014-08-08 15:07:25

标签: javascript csv d3.js functional-programming

我遇到的问题特别针对D3.js,但之前我遇到过类似的问题,并且最终总是使用黑客来解决它。

我有一个包含对象数组的类。有一个从CSV文件添加新对象的功能。使用d3.csv。此函数采用带有一个参数的文件名和回调函数(csv文件的当前解析行)。我想将每个已解析的行附加到this.objects,但this不再属于该函数的范围。

function MyClass(){
    this.objects = [];
    this.add_objects = function(filename){
        d3.csv(filename, function(data){
             //Callback fired for each parsed line in csv file

             //Now I want to push data to this.objects...

        }
    }
}

2 个答案:

答案 0 :(得分:3)

在javascript中执行此操作的常用方法是使用父作用域中的闭包变量:

function MyClass(){
    var self = this;
    this.objects = [];
    this.add_objects = function(filename){
        d3.csv(filename, function(data){
             //Callback fired for each parsed line in csv file

             // you can access self here
             self.objects.push(xxx);
        });
    }
}

或该变量可能更具体:

function MyClass(){
    this.objects = [];
    var objectArray = this.objects;
    this.add_objects = function(filename){
        d3.csv(filename, function(data){
             //Callback fired for each parsed line in csv file

             // you can access objectArray here
             objectArray.push(xxx);
        });
    }
}

或者,您可以使用.bind()(如果您不需要像IE8那样支持旧的IE)来创建一个包装器,强制为您的回调设置this

function MyClass(){
    this.objects = [];
    this.add_objects = function(filename){
        d3.csv(filename, function(data){
             //Callback fired for each parsed line in csv file
             this.objects.push(xxx);
        }.bind(this));
    }
}

答案 1 :(得分:1)

另一种方法(但更复杂)是使用bind

function MyClass(){
    this.objects = [];
    function handler(data) {        
        // here this is your binded this.
    }
    this.add_objects = function(filename){
        d3.csv(filename, handler.bind(this));
    }
}