简体   繁体   中英

JavaScript call functions within a function

I want to call a couple of functions within a init() function, where all the shared variables are stored. However, the variables won't pass to each individual function. Can anyone tell me if this is the cleanest way to do it or there is a better design for this? Thanks!

function scatterPlot(data) { /* code to do scatter plot */ }
function bestFitLine(data) { /* code to draw a regression line */ }
function drawAxes(data) { /* code to draw the axes */ }
function drawLegend(data) { /* code to draw legend */ }

function init() {
    data = { /* data object in JSON format */ }
    margin = { /* margin settings to be passed into each function */ }
    varNames = { /* some name information to be pass into each function */ }

    /* More common information to be passed */

    scatterPlot(data, margin, varNames, ...);
    bestFitLine(data, margin, varNames, ...);
    drawAxes(data, margin, varNames, ...);
    drawLegend(data, margin, varNames, ...);
}

Another way to do it would be to have data, margin, and varNames be object properties, with those four functions being methods. You'd have to change some things around to have init return an object, but it might be cleaner. Something like

function Init() {
    this.data = { /* data object in JSON format */ }
    this.margin = { /* margin settings to be passed into each function */ }
    this.varNames = { /* some name information to be pass into each function */ }

    /* More common information to be passed */

    this.scatterPlot();
    this.bestFitLine();
    this.drawAxes();
    this.drawLegend();
}

and then

Init.prototype.scatterPlot = function(data) { /* code to do scatter plot */ }
// and same with the other three

Of course this would make Init a constructor function, and would have to be called as such:

var obj = new Init();

If you don't want to, or can't do that, then what you have should be fine.

You can perhaps make one object that holds data, margin and varNames.

var ctx  = {data:{},margin:{},varNames:{}};

That makes the signature of your methods simpler.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM