Skip to content
本页目录

不要关注

各种手写源码

导航

防抖

节流

手写 new

手写 Object.create

手写 深拷贝

手写 instanceof

手写 call、apply

手写 bind

手写 Object.assign

手写 reduce

手写 AJAX

手写 柯里化

防抖

javascript
function throttle() {
    
}

节流

javascript
function

手写 new

文章可看new 做了什么

ES5 版本:

javascript
function new2(Constructor, ...args) {
  let obj = Object.create(null);
  obj.__proto__ = Constructor.prototype;
  let result = Constructor.apply(obj, args);
  return typeof result === 'object' ? result : obj;
}

ES3 版本:

javascript
function new3() {
    let obj = {},
    Constructor = Array.prototype.shift.call(arguments)
    var F = function(){}
    F.prototype = Constructor.prototype
    obj = new F()
    var result = Constructor.apply(obj, arguments)
    returb typeof result === 'object' ? result : obj
}

手写 Object.create

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

手写深拷贝

文章可看拷贝的密码

javascript
function deepClone(source, storage = new WeakMap()) {
    // 针对基本数据类型
    if (typeof source !== 'object' || source === null) {
        return source
    }
    // 是否是日期
    if (source.constructor === Date) {
        return new Date(source)
    }
    // 是否是正则
    if (source.constructor === RegExp) {
        return new RegExp(source)
    }
    // 是否是数组
    let target = source instanceof Array ? [] : {}
    // 循环引用 返回存储的引用数据
    if (storage.has(source)) return storage.get(source)
    // 开辟存储空间设置临时存储值
    storage.set(source, target)
    // 是否包含 Symbol 类型
    let isSymbol = Object.getOwnPropertySymbols(source)
    // 包含 Symbol 类型
    if (isSymbol.length) {
        isSymbol.forEach((item) => {
            if (typeof source[item] === 'object') {
                target[item] = deepClone(source[item], storage);
                return
            }
            target[item] = source[item]
        })
    }
    // 不包含 Symbol
    for(let key in source) {
        if (source.hasOwnProperty(key)) {
            target[key] = typeof source[key] === 'object' ? deepClone(sourcep[key], storage) : source[key]
        }
    }
    return target;
}

写 instanceof

文章可看instanceof——找祖籍

javascript
function myInstanceof(left, right) {
    if (typeof left !== 'object' || left === null) return false;
    let proto = Object.getPrototypeOf(left);
    while (true) {
        if (proto == null) return false;
        if (proto == right.prototype) return true;
        proto = Object.getPrototypeOf(proto);
    }
}

async/await 实现

reduce 实现

实现一个双向数据绑定

Array.isArray 实现

promise 实现

手写一个防抖/节流函数

柯里化函数的实现

高阶函数的实现

柯里化

分时函数

惰性加载

参考资料