1.構(gòu)造函數(shù)模式:返回一個新對象
constructor
通過new來實現(xiàn)
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;
}
//對象調(diào)用模式
createPerson("YQY").sayName() // YQY
createPerson("xiaoming").sayName() //xiaoming
//函數(shù)調(diào)用模式
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.模塊模式:通過閉包來實現(xiàn)一個模塊
module
var Person = (function(){
var name = "YQY";
function sayName(){
console.log(name);
}
return {
name:name,
sayName:sayName
}
})()
Person //{name:name,sayName:sayName}
6.訂閱發(fā)布模式
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
}
})();