常用设计模式
2017-08-24 本文已影响0人
8d2855a6c5d0
1.构造函数
function Person(name, age) {
this.name = name;
this.age = age;
}
Person.prototype.sayName = function() {
return this.name;
};
var student = new Person('小白', 23);
2.工厂模式 factory
function createPerson(name) {
var person = {
name: name,
sayName: function() {
console.log(this.name);
}
}
return person;
}
createPerson('xiaobai');
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('jirengu'); //{name:'jirengu'}
People.createPeople('hello'); //{name:'jirengu'}
//打印出来的都是同一个对象
匿名函数 ==>lambda
单例只返回一个对象也就一个引用,举例:对话框
词法作用域:函数的执行上下文就是函数定义的地方。
4.混合模式 mixin(继承)
function Person(name,age) {
this.name = name;
this.age = age;
}
Person.prototype.sayName = function () {
console.log(this.name);
};
function Man(name,age,sex) {
Person.call(this,name,age);
this.sex =sex;
}
var F = function () {};
F.prototype = Person.prototype;
Man.prototype = new person();
Man.prototype.saySex = function () {
console.log(this.sex);
};
5.模块模式
var Person = (function() {
var name = 'rouyu';
function sayName(name) {
console.log(name);
}
return {
name: name,
sayName: sayName
}
})();
6. 订阅发布模式
var EventCenter = (function() {
var events = {};
function on(event, handle) {
events[event] = events[event] || [];
events[event].push({
handler: handler
})
}
function fire(event, arges) {
if (!events[event]) {
return
}
for (var i = 0; i < events[event].length; i++) {
events[event][i].handler(args);
}
}
function off(name) {
delete events[name];
}
return {
on: on,
fire: fire,
//取消事件
off: off
}
})();