2011-12-11 134 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();