1.写出 构造函数模式、混合模式、模块模式、工厂模式、单例模式、发布订阅模式的范例。
构造函数模式
var Fn = function(){
this.a = 1;
this.b = 2
}
Fn.prototype.init = function(){
console.log("ok")
}
var a = new Fn;
console.log(a.init());// "ok"
混合模式
var Fn = function(){
this.a = 1;
this.b = 2;
this.init()
}
Fn.prototype.init = function(){
console.log("ok")
}
var Son = function(){}
Son.prototype=Object.creat(Fn.prototype);
Son.prototype.construct = Son
模块模式
var module = (function(){
var name = "xiaowang"
var Fn = function(){
this.a = 1;
this.b = 2;
this.init()
}
Fn.prototype.init = function(){
console.log("ok")
}
return {
init: Fn;
name: name
}
})()
工厂模式
function create( opts ){
var person ={
name: opts.name || 'hunger',
};
person.sayName: function(){
console.log(this.name)
}
return person
}
var p1 = create( { name: "xiaoming" } );
var p1 = create( { name: "xiaowang" } );
单例模式
var people = (function () {
var instance;
function init() {
return {
};
}
return {
creat: function () {
if(!instance){
instance = init()
}
return instance;
}
};
})()
发布订阅模式
var event = {};
function on( evt, handle){
evevt[evt] = evevt[evt] || [];
evevt[evt].push({
handler: handle
})
}
function fire( evt, args){
if( !evevt[evt] ){
return
}
for( var i = 0; i<evevt[evt].length; i++){
evevt[evt][i].handler(args)
}
}
function off(n){
delete enent[n];
}
return {
on: on,
fire: fire,
off: off
}
})()
EventCenter.on( "change", function(val){
console.log("change... now val is"+val)
});
EventCenter.fire("change","jirengu");
EventCenter.off("change");```
第二题参上