正如迈克已经指出的那样,是他们需要怎样被调用的差(第一个版本需要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;
}());