手写bind

45 阅读1分钟
Function.prototype.myBind = function (context) {
    //建立一个中介
    let self = this;
    //必须是函数,不是函数抛出异常
    if (typeof this !== 'function') {
        throw new Error("Function.prototype.bind - what is trying to be bound is not callable");
    

    // 建立一个空对象作为中介
    let JSONFn = function () {}
    //改变JSONFn 的指向
    JSONFn.prototype = self.prototype;
    //获取绑定参数 第一个参数是this
    let args = Array.prototype.slice.call(arguments, 1)
    //返回一个可以执行的函数
    let fn = function () {
        let fnArgs = Array.prototype.slice.call(arguments);
        return self.apply(fn instanceof this ? fn : context, args.concat(...fnArgs))
    }

    //让返回的函数 继承输入对象的属性//这样可以直接回避免修改原型
    fn.prototype = new JSONFn();
    return fn;
}