Javascript - 如何将原始对象传递给回调函数 [英] Javascript - How to pass original object to callback function

查看:125
本文介绍了Javascript - 如何将原始对象传递给回调函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到的问题与D3.js有关,但我之前遇到过类似的问题,总是使用黑客来解决它。

The problem I am having is specifically with D3.js, but I've had similar problems before and always ended up using a hack to get around it.

我有一个包含对象数组的类。有一个函数可以从CSV文件添加新对象。使用 d3.csv 。此函数接受一个文件名和一个回调函数,其中一个参数(csv文件的当前解析行)。我想将每个解析的行附加到 this.objects ,但不再在函数的作用域内。

I have a class which contains an array of objects. There is a function to add new objects from a CSV file. using d3.csv. This function takes a filename and a callback function with one argument (the current parsed line of the csv file). I want to append each parsed line to this.objects, but this is no longer within the scope of the function.

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...

        }
    }
}


推荐答案

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

A common way to do this in javascript is with a closure variable in the parent scope:

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 您的回调:

or, you can use .bind() (if you don't need to support older IE like IE8) to create a wrapper that will force the setting of this for your callback:

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));
    }
}

这篇关于Javascript - 如何将原始对象传递给回调函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆