- 写出 构造函数模式、混合模式、模块模式、工厂模式、单例模式、发布订阅模式的范例。
基本上都是通过IIFE来封装代码,进行接口的暴露
构造函数模式
var Person = function (name,sex) {
this.name = name;
this.sex = sex;
}
Person.prototype.addEvent = function () {
return this.name;
}
var person=new Person("clc","male");
var komo = function () {
this.name = "clc";
this.sex = "male";
this.addEvent();
}
komo.prototype.addEvent = function () {
console.log(this.name, this.sex);
}
new komo;
混合模式
采用继承的实现
var People = function (name, age) {
this.name = name;
this.age = age;
// this.bind();
}
People.prototype.bind = function () {
console.log("I can fly");
}
var komo=function(name,age,sex){
People.call(this,name,age,sex);
this.sex=sex;
}
komo.prototype = new People();
var clc=new komo("clc","male",23);
模块模式
var komo=(function(){
var name="clc";
sayName:function(){
console.log(name);
}
return {
name:name,
sayName:sayName,}
})()
工厂模式
简易版的构造函数模式
function creatpeople(name, sex) {
var name = name;
var sex = sex;
var run = function () {
console.log("run");
}
return {
name: name,
sex: sex,
run: run,
}
}
var a = creatpeople("komo", "male");
单例模式
相当于引用一个模块,如同js中的对象引用方式。
var People = (function () {
var instance;
function init() {
return { //do something
};
}
return {
create: function () {
if (!instance) {
instance = init();
}
return instance;
}
}
})();
var a = People.create();
var b = People.create();
// a===b ==>true
发布订阅模式
var EventCenter = (function () {
var event = {};
function on(evt, handler) {
event[evt] = event[evt] || [];
event[evt].push({
handler: handler,
})
}
function fire(evt, args) {
if (!event[evt]) {
return;
};
for (var i = 0; i < event[evt].length; i++) {
event[evt][i].handler(args);
}
}
return {
on: on,
fire: fire,
}
})()
2.使用发布订阅模式写一个事件管理器,可以实现如下方式调用
var Event = (function () {
event = {};
function on(evt, handler) {
event[evt] = event[evt] || [];
event[evt].push({
handler: handler,
})
}
function fire(evt, args) {
if (!event[evt]) {
return;
}
for (var i = 0; i < event[evt].length; i++) {
event[evt][i].handler(args);
}
}
function off(name) {
delete event[name]
}
return {
on: on,
fire: fire,
off: off,
}
})()
Event.on('change', function(val){
console.log('change... now val is ' + val);
});
Event.fire('change', '饥人谷');
Event.off('changer');