1.写出 构造函数模式、混合模式、模块模式、工厂模式、单例模式、发布订阅模式的范例。
// 工厂模式
<script>
function createPerson(opt){
var person = function(){
name = opt.name || 'huang'
}
person.sayName = function(){
console.log(this.name);
}
}
var p1 = createPerson({name:'ruoyu'});
var p2 = createPerson({name:'饥人谷'})
</script>
// 构造函数模式
<script>
function Person(name,age){
this.name = name;
this.age = age;
}
Person.prototype.sayName = function(){
return this.name;
}
var p1 = new Person('ruoyu',30);
console.log(p1);
</script>
// 模块模式
<script>
var Person = (function(){
var name = 'ruoyu';
function sayName(){
return this.name;
}
return {
name:name,
sayName:sayName
}
})();
var p1 = Person.sayName;
console.log(p1)
</script>
// 混合模式
<script>
var Person = function(name,age){
this.name = name;
this.age = age;
}
Person.prototype.sayName = function(){
console.log(this.name)
}
var Student = function(name,age,score){
Person.call(this,name,age);
this.score = score;
}
Student.prototype = create(Person.prototype);
function create(parentObject){
function fn(){};
fn.prototype = parentObject;
return new fn();
}
Student.prototype.sayScore = function(){
console.log(this.score)
}
var student = new Student('ruoyu',30,90);
console.log(student)
</script>
// 单例模式
<script>
var Person = (function(){
var instance;
function init(){
//define private methods and properties
//do something
return {
//define public methods and properties
};
}
return {
createPerson:function(){
if(!instance){
instance = init();
}
return instance;
}
}
})()
var p1 = Person.createPerson();
</script>
// 发布订阅模式
<script>
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 < event[evt].lenght; i++){
events[evt][i].handler(args);
}
}
return {
on:on,
fire:fire
}
})()
</script>
2.使用发布订阅模式写一个事件管理器,可以实现如下方式调用
Event.on('change', function(val){
console.log('change... now val is ' + val);
});
Event.fire('change', '饥人谷');
Event.off('changer');
// 实现事件管理器
<script>
var Event = (function(){
var events = {};
function on(evt,handle){
events[evt] = events[evt] || [];
events[evt].push({
handle:handle
})
}
function fire(evt,arges){
if(!events[evt]){
return;
}
for(var i = 0; i < events[evt].length; i++){
events[evt][i].handle(arges);
}
}
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', '饥人谷');
Event.off('changer');
</script>