构造函数实现单例模式 观察者模式面试题
作者:互联网
请实现EventEmitter, 让打印输出符合预期
const eventBus = new EventEmitter()
const eventBus1 = new EventEmitter()
console.log(eventBus === eventBus1) // 打印输出: true
function handleClick(param1, param2) {
console.log(param1, param2)
}
eventBus.on('click', handleClick)
eventBus.emit('click', 'foo', 'bar') // 打印输出: foo bar
function EventEmitterOrigin(){
this.fn='';//用于存触发之后的事件
this.name='click';
this.emit=(name,...arg)=>{
if(name==this.name){
this.fn(...arg)//用于发布触发存储的fn
}
}
this.on=(name,fn)=>{
this.name=name;
this.fn=fn;//用于订阅存储下fn
return this.fn
}
}
//单例模式只生成一个实例
let EventEmitter=(function(){
let fac='';
return function (){
if(!fac){
fac=new EventEmitterOrigin()
return fac
}
return fac
}
})()
// 请实现EventEmitter, 让打印输出符合预期
const eventBus = new EventEmitter()
const eventBus1 = new EventEmitter()
console.log(eventBus === eventBus1) // 打印输出: true
function handleClick(param1, param2) {
console.log(param1, param2)
}
eventBus.on('click', handleClick)
eventBus.emit('click', 'foo', 'bar') // 打印输出: foo bar
标签:面试题,name,打印输出,EventEmitter,模式,eventBus,click,fn,构造函数 来源: https://blog.csdn.net/qq_34507902/article/details/122269990