用一個對象規(guī)劃一個命名空間须误,合理的管理對象上的屬性與方法
命名空間
var niu = {
g : function(id) {
return document.getElementById(id);
},
css : function() {
this.g(id).style[...] = ...;
},
...
}
基于命名空間俏险,創(chuàng)建一個模塊分明的小型代碼庫
var A = {
Util : {
util_method1 : function() {},
util_method2 : function() {}
},
Tool : {
tool_method1 : function() {},
tool_method2 : function() {}
},
Ajax : {
get() {},
post() {}
}
}
A.Util.util_method1();
A.Tool.tool_method1();
A.Aja.get();
無法修改的靜態(tài)變量
var Conf = (function() {
var conf = {
MAX_NUM : 1000,
MIN_NUM : 1,
COUNT : 100
}
return {
get: function(name) {
return conf[name] ? conf[name] : null;
}
}
})();
// 調(diào)用靜態(tài)變量
var count = Conf.get('COUNT');
console.log(count);
惰性單例
var LazySingle = (function() {
var _instance = null;
function Single() {
return {
publicMethod : function() {},
publicProperty : '1.0'
}
}
return function() {
if (!_instance) {
_instance = Single();
}
return _instance;
}
})();
// 測試
console.log(LazySingle().publicProperty);