今天总结一下前端常用的设计模式,都是一些简单常用的设模式。
构造函数模式:
function Person(name,age) {
this.name = name;
this.age = age;
}
Person.prototype.run = function(){
console.log("I can run!");
}
Person.prototype.eat = function(){
console.log("I can eat!");
}
var Tom = new Person("Tom",22);
Tom.run();
Tom.eat();
工厂模式:
function Person(name,age){
var obj = new Object();
obj.name = name;
obj.age= age;
obj.run = function(){
console.log("I can run!");
}
obj.eat = function(){
console.log("I can eat!");
}
return obj;
}
var Tom = Person("zhaobw",22);
Tom.run();
Tom.eat();
模块模式
var Person = (function(){
function run(){
console.log("I can run!");
}
function eat(){
console.log("I can eat!");
}
return {
"run":run,
"eat":eat
}
})()
Person.run();
Person.eat();
混合模式
function Person(name,age){
this.name = name;
this.age = age;
}
Person.prototype.run = function(){
console.log("I can run!!");
}
function Student(name,age,sex){
Person.call(this,name,age);
this.sex = sex;
}
Student.prototype = create(Person.prototype);
console.log(Student.prototype);
function create(parentObj){
var obj = {};
obj.__proto__ = parentObj;
return obj;
}
var test = new Student("zhaobw",22,"man");
test.run();
单例模式
var demo = (function(){
var temp;
function init(){
return {
'name':"zhaobw"
};
}
return {
getObj:function(){
if(!temp){
temp = init();
}
return temp;
}
}
})()
var test = demo.getObj();
var test2 = demo.getObj();
console.log(test === test2);//ture
发布订阅模式
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]){
console.log("undefined");
return;
}else{
for(var i=0;i<Events[evt].length;i++){
Events[evt][i].handler(args);
}
}
}
function off(evt){
delete Events[evt];
}
return {
'on':on,
'fire':fire,
'off':off
}
})()