1.写出 构造函数模式、混合模式、模块模式、工厂模式、单例模式、发布订阅模式的范例。
//构造函数模式
function Person(name){
this.name=name
}
Person.prototype.sayHello=function(){
console.log('My name is '+this.name)
}
new Person('Tim').sayHello()//My name is Tim
//混合模式
function People(name, age) {
this.name = name;
this.age = age;
}
People.prototype.sayMyName = function() {
console.log('my name is ' + this.name);
}
//混合模式常用于实现继承
//Student继承People
function Student(name, age, major) {
People.call(this);
this.major = major;
}
//继承People的prototype
Student.prototype = Object.create(People.prototype);
Student.prototype.constructor = Student;
Student.prototype.myMajor = function() {
console.log('my major is ' + this.major);
}
var tom = new Student('tom', '11', 'run');
tom.sayMyName();
tom.myMajor();
//模块模式
var person=(function(){
var name='XiaoMing'
function sayHello(){
console.log('My name is '+this.name)
}
return{
name:name,
sayHello:sayHello
}
})()
//工厂模式
function creatPerson(opts){
opts=opts||{}
var person={
name:opts.name||'XiaoMing',
}
person.sayHello=function(){
console.log('My name is '+this.name)
}
return person
}
var p1=creatPerson({name:'Tim'})
var p2=creatPerson()
//单例模式
var people=(function(){
var name
function init(){
name='XiaoMing'
return name
}
return{
sayHello:function(name){
if(!name){
name=init()
}
return name
}
}
})()
//发布订阅模式
var Event=(function(){
var events={}
//挂载事件
function on(event,handler){
events[event]=events[event]||[]
events[event].push({
handler:handler
})
}
//触发事件
function fire(event,args){
if (!events[event]) return
for (var i = 0; i < events[event].length; i++) {
events[event][i].handler(args)
}
}
//清除事件
function off(event){
events[event]=[]
}
return{
on:on,
fire:fire,
off:off
}
})()
2.使用发布订阅模式写一个事件管理器,可以实现如下方式调用
var Event=(function(){
var events={}
//挂载事件
function on(event,handler){
events[event]=events[event]||[]
events[event].push({
handler:handler
})
}
//触发事件
function fire(event,args){
if (!events[event]) return
for (var i = 0; i < events[event].length; i++) {
events[event][i].handler(args)
}
}
//清除事件
function off(event){
events[event]=[]
}
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');
网友评论