设计模式

 惰性函数(减少浏览器无用的判断 提高性能)

function getStyle(obj,attr){
    if(obj.currentStyle){
        getStyle = function(obj,attr){
            return obj.currentStyle[attr];
        }
    }else{
        getStyle = function(obj,attr){
            return getComputedStyle(obj,false)[attr];
        }
    }
    return getStyle(obj,attr);
}

如果在某一条件下重复执行那串相同的代码可以用惰性函数

单例模式(一个类只有一个实例避免过多dom操作)

var fn=(function(){
    var div
       if(!div){    
       div=document.createElement("div")
    }
    return fn=function(){
        return div
    }
})()
var p1=fn()
var p2=fn()
console.log(p1==p2)

代理模式(代理模式(有2个对象  第二个对象想调用第一个对象里面的东西从空间里面取出))

function 我(){

}
我.prototype={
    吃饭:function(){
        console.log('我正在吃饭')
    },
    睡觉:function(){
        console.log('我正在睡觉')
    },
    学习:function(){
        console.log('我在学习')
    }
}
function 你(){
    this.你=new 我()
}
你.prototype={
    帮忙吃饭:function(money){
        if(money>100){
            this.你.吃饭()
        }
    },
    帮忙睡觉:function(money){
        if(money>200){
            this.你.睡觉()
        }
    },
    帮忙学习:function(money){
        if(money>300){
            this.你.学习()
        }
    }
}
var 帮你=new 你()
帮你.帮忙吃饭(300)

发布订阅模式

有2个对象服务端和客户端
如下:
  客户端:QQ 号 具有订阅功能
  服务端:1.将客户端加进一个数组内保存起来。
      2.通过循环向他们发送消息。

function QQ(qq){
        this.qq=qq
        this.订阅=(msg)=>{
            console.log(this.qq+'您收到消息'+msg)
        }
    }
    function server(){
        this.订阅者们=[]
    }
    $.extend(server.prototype,{
        添加订阅者(p){
            this.订阅者们.push(p)
        },
        通知(msg){
            this.订阅者们.forEach((val)=>{
                val.订阅(msg)
            })
        }
    })
    var email=new server()
    email.添加订阅者(new QQ(1323232))
    email.添加订阅者(new QQ(1323224))
    email.添加订阅者(new QQ(13213122))
    if(new Date().getHours()==18){
        email.通知('某地发生了XXX特大事故')
    }
原文地址:https://www.cnblogs.com/lianqing/p/9073556.html