js设计模式慢慢消化QAQ
设计模式
(Design Pattern)是一套被反复使用、多数人知晓的、经过分类的、代码设计经验的总结。
1.惰性函数
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <style> #box{ width: 100px; height: 100px; } </style> </head> <body> <div id="box"></div> </body> </html> <script> /* 惰性函数 */ var oBox = document.getElementById("box"); 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); } console.log(getStyle(oBox,"width")); console.log(getStyle) </script>
2.单例模式
每次创建出来的都是同一个对象
1.方式一
var fn = (function(){ var div; return function(){ if(!div){ div = document.createElement("div"); } return div; } })() console.log(fn) var a = fn(); var b = fn(); console.log(a == b);
2.方式二
function createDiv(){ if(!this.div){ createDiv.prototype.div = document.createElement("div"); } return this.div } var a = new createDiv() var b = new createDiv(); console.log(a == b)
3.方案三
var obj = {}; function fn(){ if(!obj.div){ obj.div = document.createElement("div"); } return obj.div; } var a = fn(); var b =fn(); console.log(a == b)
3.代理模式(实现图片预加载)
var myImg = (function(){ var img = document.createElement("img"); document.body.appendChild(img); return { setImg:function(src){ img.src = src } } })() var proxyImg = (function(){ //img对象 提前加载一张图片如果给这个图片加了一个src属性后就相当于在浏览器中缓存了一张图片 var image = new Image(); image.onload = function(){ alert("加载完毕") myImg.setImg(image.src); } return { setSrc:function(src){ //loding myImg.setImg("1.png"); //需要加载的图片 image.src = src; } } })() var src = "https://ss1.bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=3127448566,3364301089&fm=26&gp=0.jpg"; proxyImg.setSrc(src);
4.观察者 (发布订阅模式)
function gongsi () { this.员工们 = [] this.发工资 = function(){ for(var i in this.员工们){ this.员工们[i].工商银行(10000+Math.random()*18000); } } this.招聘 = function(p){ this.员工们.push(p); } } function Person(name){ this.name = name; this.工商银行 = function(money){ console.log(this.name+"收到"+money+"可以去大宝剑了"); } } var qianfeng =new gongsi(); qianfeng.招聘(new Person("宋磊")) qianfeng.招聘(new Person("王多")) qianfeng.招聘(new Person("杨杨")) qianfeng.招聘(new Person("钟瑞")) qianfeng.发工资()