- 写出 构造函数模式、混合模式、模块模式、工厂模式、单例模式、发布订阅模式的范例。
function Person(name){
this.name=name;
}
p1 = new Person("小明");
console.log(p1.name)
//用于实现继承
var Person = function (name,age){
this.name=name;
this.age=age;
}
var Student = function(name,age,sid){
Person.call(this,name,age);
this.sid=sid;
}
s1 = new Student("小明","12","007")
console.log(s1.name)
//使用闭包来实现作用域的隔离
var Person = (function(){
var name = '小明';
function sayName(){
console.log(name);
};
return {
name: name,
sayName: sayName
}
})();
function createpeople(name){
var Person = {
name:name,
sayName : function(){
console.log(this.name);
}
}
return Person;
}
var p1 = createpeople('小明')
p2 = createpeople('小红')
p1.sayName();
p2.sayName();
var person = (function(){
var instance;
function init(name){
return {name:name}
}
return createpeople : function(name){
if(!instance){
instance=init(name);
}
return instance;
}
}());
var EventCenter = (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);
}
}
return{
on:on,
fire:fire
}
})();
EventCenter.on('my_event',function(data){
console.log('my_event receive...')
});
EventCenter.fire('my_event');
- 使用发布订阅模式写一个事件管理器,可以实现如下方式调用
var EventCenter = (function(){
var events = {};
function on(evt,handler){
events[evt] = events[evt] || [];
events[evt].push({
handler:handler
});
}
function off(evt){
delete events[evt]
}
function fire(evt,args){
if(!events[evt]){
return;
}
for(var i=0;i<events[evt].length;i++){
events[evt][i].handler(args);
}
}
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');
网友评论