2012-04-10 127 views
3

我正在使用模式來定義「模塊」(即有效的公共靜態類)的項目,其中每個模塊都有一個init(),應在模塊定義完成後調用它。它看起來像:JavaScript模塊模式:默認值

MyNamespace.MyModule = (function() { 
    var my = {}; 
    my.init = function(config) { 
     // setup initial state using config 
    }; 
    return my; 
})(); 

我看到這個代碼庫兩種模式來定義config默認設置,不知道這是否有任何的優勢或劣勢,我不是馬上看到一個可能會更好—。建議?

這是第一個:

MyNamespace.MyModule = (function() { 
    var my = {}, 
     username, 
     policyId, 
     displayRows; 

    my.init = function(config) { 
     config = config || {}; 
     username = config.username || 'Anonymous'; 
     policyId = config.policyId || null; 
     displayRows = config.displayRows || 50; 
    }; 

    return my; 
})(); 

而這裏的第二個:

MyNamespace.MyModule = (function() { 
    var my = {}, 
     username = 'Anonymous', 
     policyId = null, 
     displayRows = 50; 

    my.init = function(config) { 
     config = config || {}; 
     username = config.username || username; 
     policyId = config.policyId || policyId; 
     displayRows = config.displayRows || displayRows; 
    }; 

    return my; 
})(); 
+0

第二個示例通過初始化您的成員,然後使用它們的默認值作爲默認值(如果配置中未提供任何內容)來遵循最佳做法。 – Maess 2012-04-10 16:21:59

+3

如果默認參數可以包含複雜對象作爲子參數,則第二種變體也更好。 – 2012-04-10 16:23:51

回答

4

沒有多大的差別,它的真正意義是什麼可讀的給你。我個人喜歡第二種方法,因爲它將默認值與邏輯分開。