functionthrottle(fn, delay){let last =0// 上次触发时间returnfunction(...args){const now = Date.now()if(now - last > delay){
last = now
fn.apply(this, args)}}}// 测试functiontask(){console.log('run task')}const throttleTask =throttle(task,1000)
window.addEventListener('scroll', throttleTask)
classParent{constructor(name){this.name = name
}eat(){console.log(this.name +' is eating')}}classChildextendsParent{constructor(name, age){super(name)this.age = age
}}// 测试let xm =newChild('xiaoming',12)console.log(xm.name)// xiaomingconsole.log(xm.age)// 12
xm.eat()// xiaoming is eating
7.发布订阅模式
classEventEmitter{constructor(){this.cache ={}}on(name, fn){if(this.cache[name]){this.cache[name].push(fn)}else{this.cache[name]=[fn]}}off(name, fn){const tasks =this.cache[name]if(tasks){const index = tasks.findIndex((f)=> f === fn || f.callback === fn)if(index >=0){
tasks.splice(index,1)}}}emit(name, once =false){if(this.cache[name]){// 创建副本,如果回调函数内继续注册相同事件,会造成死循环const tasks =this.cache[name].slice()for(let fn of tasks){fn();}if(once){deletethis.cache[name]}}}}// 测试const eventBus =newEventEmitter()consttask1=()=>{console.log('task1');}consttask2=()=>{console.log('task2');}
eventBus.on('task', task1)
eventBus.on('task', task2)
eventBus.off('task', task1)setTimeout(()=>{
eventBus.emit('task')// task2},1000)