Skip to content

手写

实现new

new Foo的过程

1、创建一个新对象,他的原型__proto__指向构造函数的prototype 2、执行构造函数,重新指定this为该新对象,并传入对应参数 3、返回一个对象,如果构造函数返回一个对象,则返回这个对象,否则返回创建的新对象

编码如下:

javascript
// 模拟new的实现
let newMock = function () {
    let argus = Array.prototype.slice.apply(arguments);
    let Foo = argus.shift();
    let target = Object.create(Foo.prototype);
    let foo = Foo.apply(target, argus);
    if (typeof foo === 'object') {
        // 比如构造函数返回了一个Object,工厂模式之类的
        return foo;
    } else {
        return target;
    }
}

// 构造函数
let Person = function (name) {
    this.name = `i am ${name}`;
    this.say = function () {
        console.log(this)
    }
}

// 使用
let p = newMock(Person, 'www')
console.log(p instanceof Person) // === true 说明newMock使用成功

实现Promise

javascript
// ...

实现bind

javascript
// 模拟bind的实现
Function.prototype.bind1 = function () {
    // 将参数拆解为数组
    const args = Array.prototype.slice.call(arguments);

    // 获取this,并从数组剔除
    const _this = args.shift();

    // 原来的fn,fn.bind(...)的fn1
    const self = this;

    // 返回一个函数
    return function () {
        return self.apply(_this, args);
    }
};

function fn () {
    console.log(this);
    console.log(arguments);
    return 'this is a fn';
}

let fn1 = fn.bind1({
    name: 'fn',
}, 10, 20);

fn1();

实现节流和防抖

  • 节流 throttle

稀释函数的执行频率

javascript
function throttle(fn, delay) {
    let lastTime = 0
    return function () {
        let now = Date.now()
        if (now - lastTime > delay) {
            fn.apply(this, arguments)
            lastTime = now
        }
    }
}
  • 防抖 debounce

固定时间不可再次触发

javascript
function debounce(fn, delay) {
    let timeout = null
    return function () {
        timeout && clearTimeout(timeout)
        timeout = setTimeout(() => {
            fn.apply(this, arguments)
        }, delay)
    }
}

实现继承

javascript
function Person1 (name) {
    this.name = name;
}
function Stu1 (name, sno) {
    Person1.call(this, name)
    this.sno = sno;
}
Stu1.prototype = Object.create(Person1.prototype)
Stu1.prototype.constructor = Stu1

实现深拷贝

实现深拷贝