单例模式:又称单体模式,是只允许实例化一次的对象类。有时候也用一个对象来规划一个明明空间,并管理对象上的属性和方法
需求1:新闻列表中做鼠标滑动特效
function g(id){ return document.getElementById(id) }
function css(id,key,value){
//简单样式属性设置
g(id).style[key] = value
}
function attr(id,key,value){ g(id)[key] = value }
function html(id,vale){ g(id).innerHTML = value }
function on(id,type,fn){ g(id)['on'+type] = fn }
问题:在全局中添加过多变量,容器引起冲突
优化1:命名空间
const Can = {
g(id){},
css(id,key,value){
//通过当前对象this来使用g方法
this.g(id).style[key] = value
},
//...
}
创建一个小型代码库
const A = {
Util:{
method1(){},
method2(){},
method3(){},
//...
},
Tool:{
method1(){},
//...
},
Ajax:{
//...
},
//...
}
A.Util.method1()
A.Tool.method1()
静态变量:函数内部定以能访问的变量,并定以一个特权方法访问
const Conf = (()=>{
//私有变量
const conf = {
MAX_NUM:100,
MIN_NUM:1,
COUNT:1000
}
// 返回取值器对象
return {
// 取值器方法
get(name){
return conf[name]?conf[name]:null
}
}
})()
// 使用
const count = Conf('COUNT')
console.log(count) // 1000
惰性单例:延迟创建单例对象
const LazySingle = (()=>{
//单例实例引用
let _instance = null
//单例
function Single(){
//这里定以私有属性和方法
return {
publicMethod(){},
publicProperty:'1.0'
}
}
// 获取单例实例对象接口
return function(){
//如果对象为创建则创建对象
if(!_instance){
_instance = Single()
}
//返回单例
return _instance
}
})()
网友评论