1.写出 构造函数模式、混合模式、模块模式、工厂模式、单例模式、发布订阅模式的范例。
构造函数模式:
function Person(name, age){
this.name = name
this.age = age
}
Person.prototype.sayName = function(){
return this.name
}
var student = new Person("若愚", 30)
console.log(student);
混合模式:
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
}
function create(parentObj){
function F(){}
F.prototype = parentObj
return new F()
}
Student.prototype = create(Person.prototype)
//Student.prototype = Object.create(Person.prototype)
Student.prototype.sayScore = function(){
console.log(this.score)
}
var student = new Student("jirengu", 28, 80)
console.log(student)
模块模式:
var Person = (function(){//通过闭包实现一个模块
var name = 'rouyu'
function sayName(){
console.name(name)
}//词法作用域
return{
name: name,
sayName: sayName
}
})()
工厂模式:
function createPerson(name){
var person = {
name: name,
sayName: function(){
console.log(this.name)
}
}
return person
}
createPerson('haha')
//每次生产一个对象,创建一个新的引用
单例模式:
var People = (function(){
var instance;
function init(name){
return{
name:name
}
}
return{
createPeople: function(name){
if (!instance){
instance = init(name)
}
return instance//是闭包中的变量
}
}
}())
People.createPeople('ruyu')//{name: 'ruyu'}
People.createPeople('hhh')//{name: 'ruyu'}
//你创建后就会一直存在,最后所有调用所指向的也是你的初始创建
发布订阅模式:
var EventCenter = (function(){
var events = {}//储存所有的key/value
function on(evt, handler){//evt事件,handler回调函数
events[evt] = events[evt] || [];
events[evt].push({
handler: handler
})
}
function fire(evt, args){//evt事件,args所有的参数
if(!events[evt]){
return
}
for(var i=0; i<events[evt].length; i++){
events[evt][i].handler(args)
}
}
function off(name){
//key/value
delete events[name]
}
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 = {}//储存所有的key/value
function on(evt, handler){//evt事件,handler回调函数
events[evt] = events[evt] || [];
events[evt].push({
handler: handler
})
}
function fire(evt, args){//evt事件,args所有的参数
if(!events[evt]){
return
}
for(var i=0; i<events[evt].length; i++){
events[evt][i].handler(args)
}
}
function off(name){
//key/value
delete events[name]
}
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');
网友评论