1. 写出构造函数模式、混合模式、模块模式、工厂模式、单例模式、发布订阅模式的范例
//单例模式范例
var Car = (function(){
var instance;
function init() {
//私有的变量和函数
var speed = 0;
return {
//定义公共的属性和方法
getSpeed: function(){
return speed;
},
setSpeed: function( s ){
speed = s;
}
};
}
return {
getInstance: function() {
if (!instance) {
instance = init();
}
return instance;
}
};
}());
var car = Car.getInstance();
var car2 = Car.getInstance();
car === car2; //true
//构造函数模式
function People(name){
this.name=name;
}
People.prototype.sayName=function(){
console.log('my name is '+this.name);
}
var people1=new People("zuo");
people1.sayName();
//混合模式--继承
function People(name){
this.name=name;
}
People.prototype.sayName=function(){
console.log('my name is '+this.name);
}
function Male(name,sex){
People.call(null,name)
this.sex=sex;
}
Male.prototype=Object.create(People.prototype);
Male.prototype.getSex=function(){
return this.sex;
}
var people2=new Male("zuo","male");
people2.sayName();
people2.getSex();
//模块模式
var People=(function(){
var people={
init:function(name,age){
this.name=name;
this.age=age;
},
sayName:function(){
console.log('my name is '+this.name);
},
setAge:function(age){
return this.age=age;
},
getAge:function(){
console.log(this.age);
}
};
return people;
}());
People.init('zuo',27);
People.sayName();
People.setAge(21);
People.getAge();
//工厂模式
var People=function(name,age){
return {
name:name,
age:age,
sayName:function(){
console.log('my name is '+this.name);
},
setAge:function(age){
this.age=age; //改为age=age也不会报错,正常输出
},
getAge:function(){
console.log(this.age);
}
}
}
var people3=People('zuo',22);
people3.sayName();
people3.getAge();
people3.setAge(27);
people3.getAge();
//发布订阅模式
var EventCenter=(function(){
var events={};
function on(evt,handler){
events[evt]=events[evt] || [];
events[evt].push({
handler:handler
})
}
function fire(evt,arg){
if(!events[evt]){
return
}
for(var i=0;i<events[evt].length;i++){
events[evt][i].handler(arg)
}
}
function off(evt){
delete events[evt];
}
return {
on:on,
fire:fire
off:off
}
}())
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,arg){
if(!events[evt]){
return
}
for(var i=0;i<events[evt].length;i++){
events[evt][i].handler(arg)
}
}
function off(evt){
delete events[evt];
}
return {
on:on,
fire:fire,
off:off
}
}());
Event.on('change', function(val){
console.log('change... now val is ' + val);
});
Event.fire('change', '饥人谷'); //change... now val is 饥人谷
Event.off('change');