工厂模式
function createPerson(opts){
var person = {};
person.name = opts.name || " Chris"
person.sayName = function(){
console.log(this.name);
}
return person;
}
var p1 = createPerson({name:"Chris"});
var p2 = createPerson({name:"kobe"});
p1.sayName();
p2.sayName();
构造函数模式
function Person(name, age){
this.name = name;
this.age = age;
}
Person.prototype.sayName = function(){
console.log(this.name);
}
// 调用
var student = new Person("Chris", 22);
student.sayName();
模块模式
var student = (function(){
var name = "Chris";
function sayName(){
console.log(name);
}
return {
name: name,
sayName: sayName
}
})()
student.sayName();
单例模式
// 构造函数的实例只有一个 可以节约内存
// 一般是通过闭包存储内部实例,通过接口访问内部实例。
var People = (function(){
var instance;
function init() {
this.a = 1;
this.b = 2;
}
return {
createPeople: function(){
if(!instance){
instance = init();
}
return instance;
}
}
})();
var obj1 = People.createPeople();
var obj2 = People.createPeople();
obj1 === obj2 // true
混合模式
// 就是在原有的对象上面增加、覆盖对象的行为。
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;
}
function inherit(superClass, slefClass){
var _prototype = Object.create(superClass.prototype);
_prototype.constructor = slefClass;
slefClass.prototype = _prototype;
}
inherit(Person, Student);
Student.prototype.sayScore = function(){
console.log(this.score);
}
var student = new Student("Chris", 22, 100);
student.sayName();
student.sayScore();
发布订阅模式
它定义了对象间的一种一对多的关系,让多个观察者对象同时监听某一个主题对象,当一个对象发生改变时,所有依赖于它的对象都将得到通知。
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
}
})();
EventCenter.on("my_event", function(data){
console.log("my_event被监控");
})
EventCenter.on("my_event2", function(data){
console.log("my_event2被监控");
})
EventCenter.fire("my_event");
网友评论