登录 注册写文章
首页下载APP
JS设计模式(6种类型)
YQY_苑关注赞赏支持JS设计模式(6种类型)
1.构造函数模式:返回一个新对象
constructor
通过new来实现
function Person(name,age){
this.name = name;
this.age = age;
}
Person.prototype.sayName = function(){
return this.name;
}
var student = new Person("YQY",22);
2.工厂模式:返回一个新对象
factory
function createPerson(name){
var person= {
name: name,
sayName:function(){
console.log(this.name);
}
};
return person;
}
//对象调用模式
createPerson("YQY").sayName() // YQY
createPerson("xiaoming").sayName() //xiaoming
//函数调用模式
var t = createPerson("YQY").sayName()
t() //undefined
//原因为createPerson中的sayName方法中的this此时指向window
3.单例模式
singleton
var People = (function(){
var instance;
function init(name){
return{
name: name
};
}
return{
createPeople : function(name){
if(!instance){
instance = init(name);
}
return instance
}
}
}());
People.createPeople("YQY") //{"name" :"YQY"}
People.createPeople("xiaoming") //{"name" :"YQY"}
4.混合模式
mix in
继承
var Person = function(name,age){
this.name = name;
this.age = age;
}
Person.prototype.sayName = function(){
console.log(this.name);
}
var Student = function(name,age,score){
Person.call(this,name,age);
this.score = score;
};
//Student.prototype = Object.create(Person.prototype)
Student.prototype = create(Person.prototype);
function create(parentObj){
function F(){}
F.prototype = parentObj;
return new F();
};
Student.prototype.sayScore = function(){
console.log(this.score);
}
var student = new Student("YQY",22,95);
5.模块模式:通过闭包来实现一个模块
module
var Person = (function(){
var name = "YQY";
function sayName(){
console.log(name);
}
return {
name:name,
sayName:sayName
}
})()
Person //{name:name,sayName:sayName}
6.订阅发布模式
publish/subscribe
var EventCenter = (function(){
var events = {};
function on(evt,handler){
events[evt] = events[evt] || [];
events[evt].push({
handler:handler
});
}
function fire(evt,args){
if(!events[evt]){
return;
}
for(var i = 0; i < events[evt].length; i++){
events[evt][i].handler(args);
}
}
function off(name){
delete events[name]
}
return{
on:on,
off:off,
fire:fire
}
})();
推荐阅读更多精彩内容
- 设计模式汇总 设计模式汇总 一、基础知识 1. 设计模式概述 定义:设计模式(Design Pattern)是一套被反复使用、多... MinoyJet阅读 2,009评论 1 赞 15
- Js 框架模块 11月中旬在伦敦举行的jQuery Summit顶级大会上有个session讲的是大型JavaScript应用程序... 牛马风情阅读 150评论 0 赞 2
- Spring 5.0.0框架介绍_中英文对照_3.4 文章作者:Tyan博客:noahsnail.com 3.4 Dependencies A typical ente... SnailTyan阅读 2,367评论 2 赞 7
- 创业过程中常见的风险及规避法则 俗话说“十个创业九个失败”,这是我们创业中常见的现象,那为什么创业失败率这么高呢?究其原因主要是因为创业风险大、风... 雪之道阅读 12,984评论 1 赞 5
- 拨开思想迷雾、给以精神力量的好书—— 《走向辉煌》 诸事繁杂,家庭失和,事业不顺,心情沉重难平,倍受忧心煎熬。苦闷中拜读了金一南将军所著《走向辉煌》。原计划安排... 玉杯清茗阅读 133评论 0 赞 0