JavaScript 手写实现合集

带立即执行的 debounce(防抖)

function debounce(fn, delay, immediate = false) {
    let timer = null;

    // 1. 内层函数:只负责每次触发时的防抖逻辑
    const _debounce = function (...args) {
        if (timer) clearTimeout(timer);

        if (immediate) {
            const callNow = !timer;
            timer = setTimeout(() => {
                timer = null;
            }, delay);
            if (callNow) fn.apply(this, args);
        } else {
            timer = setTimeout(() => {
                fn.apply(this, args);
                timer = null;
            }, delay);
        }
    };

    // 2. 在外层创建阶段就挂载 cancel(与 _debounce 平级,只创建一次)
    _debounce.cancel = function () {
        if (timer) clearTimeout(timer);
        timer = null;
    };

    // 3. 返回内层函数
    return _debounce;
}

使用示例:

const search = debounce(
    query => {
        console.log('发送搜索请求:', query);
    },
    500,
    true,
);

// 立即执行第一次
search('react'); // 立即执行
search('vue'); // 被忽略
search('angular'); // 被忽略

// 500ms 后清空定时器

// 取消防抖
search.cancel();

时间戳 + 定时器的 throttle(节流)- 首尾执行版本

纯时间戳版本的缺陷:用户在 wait 时间内连续触发后停止了操作,最后一次操作永远不会被执行(例如拖拽滚动条到最底部停下,由于最后一次触发距离上次执行不到 wait 秒,页面卡在半路没法对齐到底部)。

function throttle(fn, wait) {
    let pre = 0; // 上一次执行的时间戳
    let timer = null; // 定时器标识

    return function (...args) {
        const now = Date.now();
        // 计算距离下一次可以执行还剩多少时间
        const remaining = wait - (now - pre);

        // 情况 1:已经超过等待时间(包含第一次触发,因为 pre 初始为 0,now - 0 必然大于 wait)
        if (remaining <= 0) {
            // 如果此时刚好有一个准备尾执行的定时器,直接清掉,避免重复执行
            if (timer) {
                clearTimeout(timer);
                timer = null;
            }
            fn.apply(this, args);
            pre = now;
        }
        // 情况 2:还在冷却期内,且当前没有排队的尾执行定时器,则挂一个定时器兜底"最后一次"
        else if (!timer) {
            timer = setTimeout(() => {
                // 注意:尾执行触发时,更新 pre 为当前执行时间,保证下一次触发重新计算冷却期
                pre = Date.now();
                timer = null;
                fn.apply(this, args);
            }, remaining);
        }
    };
}

使用示例:

const resize = throttle(() => {
    console.log('窗口大小变化');
}, 300);

window.addEventListener('resize', resize);

myNew - 模拟 new 关键字

new 关键字主要做了以下事情:

  1. 创建一个空对象,并设置其原型为构造函数的原型
  2. 获取构造函数的返回值(通过 apply 方法传递参数)
  3. 判断该值是不是对象,如果是,返回它,否则返回第一步创建的对象

构造函数内部显式 return 的规则:

  1. 如果是对象,返回该对象
  2. 否则返回创建的空对象
const myNew = (constructor, ...args) => {
    // 边界校验:确保传入的是函数
    if (typeof constructor !== 'function') {
        throw new TypeError('Constructor is not a function');
    }

    const obj = {};
    // 设置原型
    Object.setPrototypeOf(obj, constructor.prototype);
    // 获取构造函数的返回值
    const res = constructor.apply(obj, args);
    // 构造函数的返回值若是对象,返回它,否则返回 obj
    return res instanceof Object ? res : obj;
};

更严谨的返回值判断(跨 realm 场景):

const myNew = (constructor, ...args) => {
    if (typeof constructor !== 'function') {
        throw new TypeError('Constructor is not a function');
    }

    const obj = {};
    Object.setPrototypeOf(obj, constructor.prototype);
    const res = constructor.apply(obj, args);

    // 跨 iframe/realm 场景下 instanceof Object 可能失效
    // 更严谨写法:
    return (typeof res === 'object' && res !== null) || typeof res === 'function' ? res : obj;
};

myInstanceof - 模拟 instanceof 运算符

原理:

  1. 左侧为非对象时(基本类型或 null),直接返回 false
  2. 先获取右侧的 prototype(没有时抛出异常),然后不断获取左侧的原型(通过原型链),每获取一次就和右侧的 prototype 比对一次,严格相等时返回 true,左侧直到 null 都没比对成功返回 false
  3. 如果右侧实现了 Symbol.hasInstance 的静态方法,就直接返回 hasInstance 的返回值
function myInstanceof(left, right) {
    // 1. 基本类型或 null 直接返回 false
    if (left === null || (typeof left !== 'object' && typeof left !== 'function')) {
        return false;
    }

    // 2. 支持 ES6 Symbol.hasInstance
    if (typeof right[Symbol.hasInstance] === 'function') {
        return Boolean(right[Symbol.hasInstance](left));
    }

    // 3. 边界校验:右侧必须是对象
    if (typeof right !== 'object' || right === null) {
        throw new TypeError("Right-hand side of 'instanceof' is not an object");
    }

    let proto = Object.getPrototypeOf(left); // 等同于 left.__proto__
    const prototype = right.prototype;

    while (proto !== null) {
        if (proto === prototype) return true;
        proto = Object.getPrototypeOf(proto);
    }
    return false;
}

继承演进历史

ES6 之前为了模拟类继承经历了几个阶段:

  1. 原型链继承:痛点是所有实例共享父类的引用属性(改一个全变)且无法向父类传参
  2. 构造函数继承(在子类里 Parent.call(this)):解决了传参和属性共享,但痛点是父类原型上的方法无法复用,每次实例化都要重新创建函数
  3. 寄生组合式继承:把两者结合——用 Parent.call(this) 继承实例属性,再用 Object.create(Parent.prototype) 让子类原型指向父类原型的副本,既避免了调用两次父类构造函数,又完整继承了原型方法。这也是 Babel 编译 ES6 class extends 的底层实现。

myBind - 模拟 bind 方法

Function.prototype.myBind = function (obj, ...args) {
    // 边界校验:确保调用 myBind 的是函数
    if (typeof this !== 'function') {
        throw new TypeError('Function.prototype.myBind must be called on a function');
    }

    const func = this;
    return function F(...args2) {
        // 判断 F 调用的方式,是使用 new 调用,还是普通调用
        return this instanceof F ? new func(...args, ...args2) : func.apply(obj, [...args, ...args2]);
    };
};

完善版(设置原型链):

Function.prototype.myBind = function (obj, ...args) {
    if (typeof this !== 'function') {
        throw new TypeError('Function.prototype.myBind must be called on a function');
    }

    const func = this;
    const F = function (...args2) {
        return this instanceof F ? new func(...args, ...args2) : func.apply(obj, [...args, ...args2]);
    };

    // 设置原型链,使 new F() 创建的实例能继承 func.prototype 上的方法
    F.prototype = func.prototype;

    return F;
};

myCall / myApply - 模拟 call 和 apply

myCall

Function.prototype.myCall = function (context, ...args) {
    // 边界校验:确保调用 myCall 的是函数
    if (typeof this !== 'function') {
        throw new TypeError('Function.prototype.myCall must be called on a function');
    }

    // 处理 null/undefined(指向 globalThis)及基本数据类型(包装为对象实例)
    const targetContext = context === null || context === undefined ? globalThis : Object(context);

    // 使用 Symbol 生成绝对唯一的属性名,避免覆盖 targetContext 上原有的同名属性
    const fnSymbol = Symbol('tempFn');
    // 将当前函数(this)挂载到目标上下文上
    targetContext[fnSymbol] = this;

    try {
        return targetContext[fnSymbol](...args);
    } finally {
        delete targetContext[fnSymbol];
    }
};

myApply

Function.prototype.myApply = function (context, argsArray) {
    if (typeof this !== 'function') {
        throw new TypeError('Function.prototype.myApply must be called on a function');
    }

    // 处理 context
    const targetContext = (context === null || context === undefined)
        ? globalThis
        : Object(context);

    // Symbol 隔离挂载
    const fnSymbol = Symbol('tempFn');
    targetContext[fnSymbol] = this;

    try {
        // 处理 apply 的第二个参数:未传、null 或 undefined 时直接无参调用
        if (argsArray === null || argsArray === undefined) {
            return targetContext[fnSymbol]();
        }

        // 规范校验:如果传了第二个参数但不是对象(如数字、布尔值、字符串),原生 apply 会抛出 TypeError
        if (typeof argsArray !== 'object' && typeof argsArray !== 'function') {
            throw new TypeError('CreateListFromArrayLike called on non-object');
        }

        // 支持数组及类数组对象(如 arguments)的展开传递
        return targetContext[fnSymbol](...Array.from(argsArray));
    } finally {
        delete targetContext[fnSymbol];
    }
};
    } finally {
        delete targetContext[fnSymbol];
    }
};

deepClone - 深拷贝

相当于 structuredClone(obj) 的手写实现。

function deepClone(target, map = new WeakMap()) {
    // 1. 基本数据类型或函数(函数一般直接复用引用),直接返回
    if (target === null || typeof target !== 'object') {
        return target;
    }

    // 2. 处理循环引用:如果 map 中已经记录过该对象,直接返回对应的克隆体,防止死循环爆栈
    if (map.has(target)) {
        return map.get(target);
    }

    // 3. 处理特殊内置对象:Date 和 RegExp
    if (target instanceof Date) {
        return new Date(target.getTime());
    }
    if (target instanceof RegExp) {
        return new RegExp(target.source, target.flags);
    }

    // 4. 处理 Map
    if (target instanceof Map) {
        const cloneMap = new Map();
        map.set(target, cloneMap); // 必须先存入 map 再递归,防止 Map 内部自引用
        target.forEach((value, key) => {
            cloneMap.set(deepClone(key, map), deepClone(value, map));
        });
        return cloneMap;
    }

    // 5. 处理 Set
    if (target instanceof Set) {
        const cloneSet = new Set();
        map.set(target, cloneSet);
        target.forEach(value => {
            cloneSet.add(deepClone(value, map));
        });
        return cloneSet;
    }

    // 6. 处理数组和普通对象(保留原对象的原型链结构)
    const cloneTarget = Array.isArray(target) ? [] : Object.create(Object.getPrototypeOf(target));

    // 必须在递归遍历属性前先写入 WeakMap!
    map.set(target, cloneTarget);

    // 7. 使用 Reflect.ownKeys 遍历所有自身属性(包含不可枚举属性和 Symbol 类型的 key,且不遍历原型链)
    Reflect.ownKeys(target).forEach(key => {
        cloneTarget[key] = deepClone(target[key], map);
    });

    return cloneTarget;
}

说明:

  • WeakMap 对键是弱引用,一旦 deepClone 执行结束、外部不再引用原对象,GC 可以自动回收这些临时映射,防止深拷贝大对象后造成内存泄漏
  • 此实现覆盖了常见类型(对象、数组、Date、RegExp、Map、Set),但未覆盖 WeakMap/WeakSet/ArrayBuffer/TypedArray/Error/Promise 等特殊类型,可作为已知局限

myFlat - 数组扁平化

迭代版本(避免递归深度限制),支持稀疏数组。

function myFlatIterative(arr, depth = 1) {
    const result = [];
    // 栈中存放元组:[当前元素,剩余可展开深度]
    // 注意:为了跳过稀疏数组空位,使用 Object.keys 或 forEach 遍历初始层
    const stack = [];
    arr.forEach(item => {
        stack.push([item, depth]);
    });

    while (stack.length > 0) {
        const [current, currentDepth] = stack.pop();

        if (Array.isArray(current) && currentDepth > 0) {
            // 倒序遍历压栈,保证弹出时依然维持原有的从左到右顺序,且 forEach 自动忽略空位
            for (let i = current.length - 1; i >= 0; i--) {
                if (i in current) {
                    // 严谨过滤稀疏数组空槽
                    stack.push([current[i], currentDepth - 1]);
                }
            }
        } else {
            result.push(current);
        }
    }

    return result;
}

并发请求限制调度器

实现同时最多执行 max 个请求的调度器(详见《Promise 详解》博文中的使用示例)。

const limitRequest = (tasks, max = 3) => {
    return new Promise(resolve => {
        if (!Array.isArray(tasks) || tasks.length === 0) {
            resolve([]);
            return;
        }

        const limit = Math.max(1, Math.floor(max));
        const results = new Array(tasks.length);
        let index = 0; // 下一个请求的下标
        let count = 0; // 当前请求完成的数量

        const run = async () => {
            if (index === tasks.length) {
                return;
            }
            const i = index; // 保存当前任务序号
            const task = tasks[index];
            index++;

            try {
                const resp = await task();
                results[i] = resp;
            } catch (err) {
                results[i] = err;
            } finally {
                count++;
                if (count === tasks.length) {
                    resolve(results);
                }
                run();
            }
        };

        const times = Math.min(limit, tasks.length);
        for (let i = 0; i < times; i++) {
            run();
        }
    });
};

EventEmitter - 事件发布订阅

class EventEmitter {
    constructor() {
        this.events = Object.create(null); // 用无原型纯净对象
    }

    on(eventName, fn) {
        if (!this.events[eventName]) this.events[eventName] = [];
        this.events[eventName].push(fn);
    }

    off(eventName, fn) {
        const callbacks = this.events[eventName];
        if (!callbacks) return;
        if (!fn) {
            delete this.events[eventName];
            return;
        }
        // 既能匹配普通 fn,也能匹配 once 包装后的 wrapper.originFn
        this.events[eventName] = callbacks.filter(cb => cb !== fn && cb.originFn !== fn);
    }

    emit(eventName, ...args) {
        const callbacks = this.events[eventName];
        if (!callbacks) return;
        // 浅拷贝一份再遍历,彻底杜绝回调内部调用 off 导致的数组塌陷
        [...callbacks].forEach(cb => cb.apply(this, args));
    }

    once(eventName, fn) {
        const wrapper = (...args) => {
            fn.apply(this, args);
            this.off(eventName, wrapper);
        };
        wrapper.originFn = fn; // 挂载原函数引用,支持提前 off(eventName, fn)
        this.on(eventName, wrapper);
    }
}

使用示例:

const emitter = new EventEmitter();

// 订阅
emitter.on('data', data => {
    console.log('收到数据:', data);
});

// 订阅一次性事件
emitter.once('end', () => {
    console.log('结束');
});

// 触发
emitter.emit('data', { id: 1 });
emitter.emit('data', { id: 2 });
emitter.emit('end');
emitter.emit('end'); // 不会触发

// 取消订阅
emitter.off('data');

JavaScript 手写实现合集
https://www.reimu747.ink/post/20230301.html
作者
Reimu747
发布于
2023年3月1日
许可协议