Reputation: 5167
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, ...);
}
Upvotes: 1
Views: 77
Reputation: 39278
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.
Upvotes: 1
Reputation: 83376
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.
Upvotes: 1