前端面试手写篇(二)

这篇博客探讨了JavaScript中常见的性能优化技巧,包括防抖(debounce)和节流(throttle)函数的实现,用于优化事件处理函数的执行。同时,还介绍了如何实现深拷贝功能以及发布订阅者模式(EventEmitter),用于在代码中实现组件间的通信。这些技巧对于提升JavaScript应用的性能和可维护性至关重要。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

防抖:在事件被触发n秒后再执行回调,如果在这n秒内又被触发,重新计数

function debounce(fn,wait=500){
    let timer = null;
    return function(...args){
        if(timer){
            clearTimeout(timer)
        }
        timer = setTimeout(()=>{
            fn.apply(this,args)
        }, wait);
    }
}

节流:规定时间内只能触发依次函数,如果多次触发只有依次生效

function throttle(fn,wait=500){
    let timer = null;
    return function(...args){
        if(!timer){
            timer = setTimeout(() => {
                fn.apply(this,args)
                timer = null;
            }, wait);
        }
    }
}

深拷贝

function deepClone(obj){
    if(typeof obj !== 'object' || obj === null){
        return obj
    }
    let copy = {};
    if(obj instanceof Array){
        copy = []
    }
    for(key in obj){
        if(obj.hasOwnProperty(key)){
            copy[key] = deepClone(obj[key])
        }
    }
    return copy;
}

发布订阅者模式

class EventEmitter{
    constructor(max){
        this._events = new Map();//存储事件
        this.maxListeners = max || 10;
    }

    addListener(type,fn){
        if(typeof fn !== 'function'){
            throw new Error('the Second parameter expected a function')
        }
        const handler = this._events.get(type);
        if(!handler){
            this._events.set(type,[fn])
        }else{
            if(handler.length===this.maxListeners){
                throw new Error('this length of listeners can not exceed the max')
            }
            handler.push(fn)
            this._events.set(type,handler);
        }
    }

    emit(type,...args){
        const handlers = this._events.get(type);
        if(!handlers){
            throw new Error('you only can emit a listener which you have added')
        }else{
            handlers.forEach((fn)=>{
                fn.apply(this,args);
            })
        }
    }

    remove(type,fn){
        const handlers = this._events.get(type);
        let position = handlers.indexOf(fn);
        if(position>-1){
            handlers.splice(position,1)
            this._events.set(type,handlers);
        }
    }
}

//测试

let emitEve = new EventEmitter(3);
function test1(){
    console.log('测试1')
}
function test2(){
    console.log('测试2')
}
function test3(){
    console.log('测试3')
}
emitEve.addListener('test',test1)
emitEve.addListener('test',test2)
emitEve.addListener('test',test3)
emitEve.remove('test',test1)
emitEve.emit('test')

模拟Object.create

function create(proto){
    function F(){}
    F.prototype = proto;
    return new F();
}

实现类的继承

function Parent(name,gendar,family){
    this.name = name;
    this.gendar = gendar;
    this.family = family
}
Parent.prototype.sayHello = function(){
    console.log('用中国话说hello');
}
function Child(name,gendar,family,like){
    Parent(name,gendar,family);
    this.like = like;
}
function inherit(parent,son){
    son.prototype = Object.create(parent.prototype)
    son.prototype.constructor = son;
    son.prototype.uber = parent.prototype;
}
inherit(Parent,Child)

实现JSON.stringify

function myJsonStringify(obj){
    let type = typeof(obj);
    if(type !== 'object'){
        if(/number/.test(type)){
            return obj;
        }else{
            return String(obj)
        }
    }
    let json = []
    let isArr = Array.isArray(obj);
    for( key in obj ){
        let v = obj[key];
        let type = typeof(obj[key])
        if(/string|undefined|function/.test(type)){
            v = '"'+v+'"';
        }else if(type === "object"){
            v = myJsonStringify(v);
        }
        json.push((isArr?"":'"'+key+'"')+String(v));
    }
    return (isArr ? "[" : "{") + String(json) + (isArr ? "]" : "}")
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值