2014-05-01 135 views
1

我想調用init()函數中的幾個函數,其中存儲了所有共享變量。但是,這些變量不會傳遞給每個單獨的函數。任何人都可以告訴我,如果這是最乾淨的方式,或者有更好的設計?謝謝!函數中的JavaScript調用函數

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, ...); 
} 
+0

將所有內容都包含在另一個擁有共享變量的函數中? –

回答

1

另一種方法是將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 

東西當然,這將使初始化一個構造函數,並且將不得不被稱爲例如:

var obj = new Init(); 

如果你不想到或不能這樣做,那麼你有什麼應該沒問題。

1

你也許可以讓一個對象保存數據,邊距和varNames。

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

這使得您的方法的簽名更簡單。