1.写出 构造函数模式、混合模式、模块模式、工厂模式、单例模式、发布订阅模式的范例。
-
构造函数模式
function Person (name,age){ this.name = name this.age = age } Person.prototype.sayName = function(){ return this.name } var haoRan = new Person('浩然',24)
-
混合模式
var Person = function(name,age) { this.name = name this.age = age } Person.prototype.sayName = function(){ return this.name } var Student = function(name,age,score){ Person.call(this,name,age) this.score = score } Student.prototype = create(Person.prototype) Student.prototype.sayScore = function(){ console.log(this.score) } function create(parentObj){ function F(){} F.prototype = parentObj return new F(); } var haoRan = new Student('浩然',24,100)
-
模块模式
var Person = (function(){ var name = '浩然' function sayName(){ console.log(name) } return { name:name, sayName:sayName } })()
-
工厂模式
function createPerson(name,age){ var person = { name: name, age: age, sayName: function(){ return this.name } } return person } var haoRan = createPerson('浩然',24)
-
单例模式
var Person = (function(){ var instance function init(name,age){ return { name: name, age: age } } return { createPerson: function(name,age){ if(!instance){ instance = init(name,age) } return instance } } }()) var haoRan = Person.createPerson('浩然',24)
-
发布订阅模式
var EventCenter = (function(){ var events = {} function on (evt ,handler){ events[evt] = events[evt] || [] events[evt].push({ handler: handler }) } function fire(evt,args){ if(!event[evt]){ return } for(var i=0;i<events[evt].length;i++){ events[evt][i].handler(args) } } return { on: on, fire: fire } })()
2.使用发布订阅模式写一个事件管理器,可以实现如下方式调用
Event.on('change', function(val){
console.log('change... now val is ' + val);
});
Event.fire('change', '饥人谷');
Event.off('changer');
var Event = (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){
if(!events[evt]){
console.log('此名称下没有方法...')
return
}else {
events[evt] = undefined
}
}
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');
Event.off('change');
/**
* 输出:
* change... now val is 饥人谷
* 此名称下没有方法...
*/