2011-12-11 94 views
1

就是下面的區別:的JavaScript模塊模式

function test(){ 
    this.init=function(){//do something} 
    this.some=function(){//do something} 
    function other(){} 
} 

function test(){ 
    function init(){//do something} 
    function some(){//do something} 
    function other(){} 

    return {'init':init, 'some':some}; 
} 

感謝解釋。

回答

4

正如邁克已經指出的那樣,是他們需要怎樣被調用的差(第一個版本需要new而第二個則不)。這就是說,如果這些被用於實際模塊(而不是僅僅是對象),並且模塊中的功能互相調用,那麼就會有所不同。

在第二種情況下,函數可以直接引用對方(靜態綁定)。

function init(){ 
    some(17); 
} 

但在第一種情況下,他們將通過動態相互引用通過this綁定:

this.init = function(){ 
    this.some(17); 
} 

這意味着,在第一種情況下(與this)init函數必須始終稱爲爲module.init(),不能傳遞給回調

setTimeout(module.init, 1000); 
//this line will does not work with the `this.init` variation 
//but will work fine in the second version 

因爲我不喜歡不必重新輸入功能名稱與第二版一樣,我個人更喜歡在我的模塊中使用以下樣式:

var module = (function(){ 

    var M = {}; //private namespace. 
       //decouples from the actual name and I 
       //can always use the same letter (for consistency) 

    M.init = function(){ 
     M.some(17); 
    }; 

    M.some = function(){ 
     // 
    } 

    function other(){ ... } 

    return M; 
}()); 
6

第一個例子:

var object = new test(); 
object.init(); 

第二個例子:

var object = text(); // no new 
object.init();