Javascript设计模式(一)
1.单例模式
javascript 单例模式定义命名空间
// 定义命名空空间
var Ming={
g:function(id){
return document.getElementById(id)
},
css:function(id,key,value){
this.g(id).style[key]=value;
}
}
console.log(Ming.g("box"));
Ming.css("box","width","200px");
Ming.css("box","height","200px");
Ming.css("box","background","red");
避免变量的冲突定义自己的命名空间。
// 规范自己的代码库
var G={
Util:{
util_method1:function(){},
util_method2:function(){}
},
Tool:{
tool_method1:function(){},
tool_method2:function(){}
},
Ajax:{
get:function(){},
post:function(){}
},
Other:{
other_method1:function(){},
other_method2:function(){}
}
}
//G.Ajax.get()
//G.Tool.tool_method1();
//定义无法修改的静态变量
var Conf=(function(){
var conf={
MAX_NUM:100,
MIN_NUM:1,
COUNT:1000
}
return{
get:function(name){
return conf[name]?conf[name]:null;
}
}
})();
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);

浙公网安备 33010602011771号