1.写出 构造函数模式、混合模式、模块模式、工厂模式、单例模式、发布订阅模式的范例。
//单例模式
var Car = (function () {
var instance;
function init() {
var speed = 0;
return {
getSpeed: function () {
return speed;
},
setSpeed: function (val) {
speed = val;
}
}
}
return {
getInstance: function () {
if (!instance) {
instance = init();
console.log(instance);
}
return instance;
}
};
}())
var car = Car.getInstance();
var car2 = Car.getInstance();
//构造函数模式
function People(name){
this.name=name;
}
People.prototype.sayName=function(){
console.log("my name is"+this.name);
}
var people=new People("haha");
people.sayName();
//混合模式
function People(name) {
this.name = name;
this.sayName = function () {
console.log("my name is " + this.name);
}
}
function Male(name, sex) {
People.call(this, name);
this.sex = sex;
}
Male.prototype.getSex = function () {
console.log(this.sex);
return this.sex;
}
var people = new Male("haha", "male");
people.sayName();
people.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('haha',24);
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;
},
getAge:function(){
console.log(this.age);
}
}
}
var people=People('haha',22);
people.sayName();
people.getAge();
people.setAge(27);
people.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
}
}())