我想在 init()
函数中调用几个函数,其中存储了所有共享变量。但是,变量不会传递给每个单独的函数。谁能告诉我这是最干净的方法还是有更好的设计?谢谢!
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, ...);
}
最佳答案
另一种方法是让 data、margin 和 varNames 成为对象属性,这四个函数成为方法。你必须改变一些东西才能让 init 返回一个对象,但它可能更干净。有点像
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();
}
然后
Init.prototype.scatterPlot = function(data) { /* code to do scatter plot */ }
// and same with the other three
当然这会使 Init 成为构造函数,并且必须这样调用:
var obj = new Init();
如果您不想或不能那样做,那么您拥有的应该没问题。
关于函数内的 JavaScript 调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23416118/