1.构造函数模式
function Person(name, age){
this.name = name;
this.age = age;
}
Person.prototype.sayName = function(){
console.log(this.name);
}
var xiaoming = new Person("小明", 11);
xiaoming.sayName()
2.混合模式
一般是混合原型(在一个构造函数里调用另一个构造函数的方法)。
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 = create(Person.prototype);
function create (parentObj){
function F(){}
F.prototype = parentObj;
return new F();
};
Student.prototype.getScore = function(){
console.log(this.score);
}
var xiaoming = new Student("小明", 11, 66);
console.log(xiaoming);
3.模块模式
var Person = (function(){
var name = '小明';
function sayName(){
console.log(name);
}
return {
name: name,
sayName: sayName
}
})()
console.log(Person.name);
Person.sayName();
4.工厂模式
function createPerson(people){
var person = {
name: people.name||'hunger'
};
person.sayName: function(){
console.log(this.name);
}
return person;
}
var p1 = createPerson({name:'小明'});
var p2 = createPerson({name: '小红'});
5.单例模式
var People = (function(){
var instance;
function init() {
return {
instance = "hunman"
};
}
return {
createPeople: function() {
if (!instance) {
instance = init();
}
return instance;
}
};
}())
var obj1 = People.createPeople();
6.发布订阅模式
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(evt){
delete events[evt]
}
return {
on: on,
fire: fire,
off: off
}
})();