- 寫出 構造函數模式、混合模式、模塊模式、工廠模式、單例模式、發布訂閱模式的范例。
基本上都是通過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');