当面试官要你手写一个bind时

49 阅读1分钟

要开始写了

// 1.手写一个bind
Function.prototype._bind = function (context, ...args) {
    // 1. 将原来的this,也就是函数本身,临时存储
    const _this = this
    // 2. 接收一个新的this
    const newThis = context
    // 3. 注意bind返回的是一个未执行的函数
    return function () {
       //4.调用_apply 并将新的this和参数传递过去
        return _this._apply(newThis, args)
    }

}

// 2.bind会调用 `_apply` 方法。所以顺手写一个
Function.prototype._apply = function (context, args) {
        // 非函数抛出error
        if (typeof this !== 'function') {
            return new TypeError('非函数')
        }

        // 兜底操作防止this为空
        context = context || window


        // 接收原始this函数本身 ,使用symbol为key存储确保唯一
        const fnSymbol = Symbol()
        context[fnSymbol] = this

        // 调用函数
        const result = args ? context[fnSymbol](...args) : context[fnSymbol]()

        delete context[fnSymbol]

        return result

    }

下面来执行一下


    function Hello(name) {
        console.log(`Hello, ${name}! My name is ${this.name}`);
    }

    const person = { name: 'zhangsan' };

    const boundHello = Hello._bind(person, 'laoli');
    boundHello();//=>Hello, laoli ! My name is zhangsan



    function add(a, b) {
        return a + b;
    }


    add._apply(null, [1, 2]) //=>3

写完了就是这么朴实无华。