用做命名空间的对象
在模块创建过程中使用对象作为命名空间可以避免污染全局变量。它将函数和值作为对象的属性存取起来。
var com;
if (!com)
com = {};
if (!com.my)
com.my = {};
if (!com.my.collections)
com.my.collections = {};
if (!com.my.collections.Sets)
com.my.collections.Sets = {};
// 在命名空间总存放供外部访问的API
Sets.Set = Set;
Sets.SubSet = SubSet;
作为私有命名空间函数
有些函数是只供内部使用而不作为API提供的,对于这样的函数我们将其私有,只有在命名空间中可以访问。
Set = (function(){
function Set(){
this.values={};
...
}
// 这个函数只能在这个代码块中被访问。
funciton a(){/*函数体*/};
Set.prototype.func = function(){
// code
a();
// code
};
return Set
}());