今天小编就为大家带来一篇介绍javascript的设计模式的文章。小编觉得挺实用的,为此分享给大家做个参考。一起跟随小编过来看看吧。

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");

以上就是javascript的设计模式的详细内容了,看完之后是否有所收获呢?如果想了解更多相关内容,欢迎关注亿速云行业资讯!