1.工厂模式
优点 避免创建多次对象

function Factory(n,s){         //创建一个对象         var obj={};         obj.name=n;         obj.sex=s;         obj.sleep=function (){             return this.name+"睡觉";         }         return obj;     }      console.log(Factory("李四", "男"));

2构造函数模式
接定义函数 this(指针) 指向当前实例的对象
里面的方法和属性直接写 this.***
没有明显的创建对象 没有返回值

function Page(){         this.nowpage=1;         this.totlepage=20;         this.data=null;         this.createpageLi=function (){             console.log("构造函数模式的方法");         }     }      //实例化对象     var page=new Page();

3原型模式

function Person() {      }     //原型独享的属性和方法的     Person.prototype = {         name: "",         sex: "",         sleep: function (m) {             return this.name + "睡觉" + m;         }     }     var per1 = new Person();     per1.name = "张三";     per1.sex = "男";     console.log(per1);

4单例模式
一个类仅提供一个实例 并且暴露出一个全局访问点
//设置多个类对象 将单例方法抽为一个共享方法

function Person(name) {         this.name = name;     }     Person.prototype.getName = function () {         return this.name;     }     var getInstance = function (callback) {         var instance = null;         //注意里面的闭包         return function () {//不写形参  直接使用arguments  集合列表              if (!instance) {                 //实例化对象的                  /*callback 是回调函数  返回一个对象                  apply  call    替换对象的时候可以直接执行函数*/                 instance = callback.apply(this, arguments);             }             return instance;         }     }      console.log(getInstance(function () {         //这个匿名函数内部返回一个对象         var per = new Person("李四");         return per;     })().getName());      function Animal(name) {         this.name = name;     }     Animal.prototype.getName = function () {         return this.name;     }      var method = getInstance(function (name) {         //这个匿名函数内部返回一个对象         var animal = new Animal(name);  //刚才在这里直接给name赋值了         return animal;     });      console.log(method("猫咪").getName());     console.log(method("小黑").getName());      //call  apply  替换对象this的  传递参数  call 参数是this ,序列参数    apply 参数this ,集合参数

5策略模式
策略模式是将算法和 算法的使用分离

//策略     var levelable={         S:8,         A:6,         B:4,         C:2,         D:0     }     //策略使用   策略集合     var levelScore={         baseScore:70,         S:function (){              return this.baseScore+levelable["S"];         },         A:function (){             return this.baseScore+levelable["A"];         },         B:function (){             return this.baseScore+levelable["B"];         },         C:function (){             return this.baseScore+levelable["C"];         },         D:function (){             return this.baseScore+levelable["D"];         }     }     //得分情况     function getScore(score,level)     {   levelScore.baseScore=score;         console.log(levelScore[level]());     }      getScore(60,"S");
  • 版权声明:文章来源于网络采集,版权归原创者所有,均已注明来源,如未注明可能来源未知,如有侵权请联系管理员删除。

发表回复

后才能评论