面试常谈之手写newcallapply和bind

16次阅读

共计 2113 个字符,预计需要花费 6 分钟才能阅读完成。

面试常谈之手写 new、call、apply 和 bind

new

function myNew(){
    // 创建一个空对象
    let obj = new Object();
    // 获取构造函数
    let Constructor = [].shift.call(arguments);
    // 链接到原型
    obj.__proto__ = Constructor.prototype;
    // 绑定 this 值
    let result = Constructor.apply(obj,arguments);// 使用 apply,将构造函数中的 this 指向新对象,这样新对象就可以访问构造函数中的属性和方法
    // 返回新对象
    return typeof result === "object" ? result : obj;// 如果返回值是一个对象就返回该对象,否则返回构造函数的一个实例对象
  }

可以概括为以下四步:
1. 创建一个空对象
2. 链接到原型
3. 绑定 this 值
4. 返回新对象

call

这里提供两种写法

Function.prototype.myCall = function(obj, ...arg){
    // 我们要让传入的 obj 成为, 函数调用时的 this 值.
    obj._fn_ = this;  // 在 obj 上添加_fn_属性,值是 this(要调用此方法的那个函数对象)。obj._fn_(...arg);       // 在 obj 上调用函数, 那函数的 this 值就是 obj.
    delete obj._fn_; // 再删除 obj 的_fn_属性, 去除影响.
    //_fn_ 只是个属性名 你可以随意起名,但是要注意可能会覆盖 obj 上本来就有的属性
}
Function.prototype.myCall = function(obj){if(obj === null || obj === undefined){obj = window;} else {obj = Object(obj);
    }
    let arg = [];
    for(let i = 1 ; i<arguments.length ; i++){arg.push( 'arguments[' + i + ']' ) ;
        // 这里要 push 这行字符串  而不是直接 push 值
        // 因为直接 push 值会导致一些问题
        // 例如: push 一个数组 [1,2,3]
        // 在下面???? eval 调用时, 进行字符串拼接,JS 为了将数组转换为字符串,// 会去调用数组的 toString() 方法, 变为 '1,2,3' 就不是一个数组了,相当于是 3 个参数.
        // 而 push 这行字符串,eval 方法,运行代码会自动去 arguments 里获取值
    }
    obj._fn_ = this;
    eval('obj._fn_(' + arg + ')' ) // 字符串拼接,JS 会调用 arg 数组的 toString() 方法,这样就传入了所有参数
    delete obj._fn_;
}

apply

apply 的写法跟 call 接近

Function.prototype.myApply = function(obj,arr){if(obj === null || obj === undefined){obj = window;} else {obj = Object(obj);
    }
    let args = [];
    let val ;
    for(let i = 0 ; i<arr.length ; i++){args.push( 'arr[' + i + ']' ) ;
    }
    obj._fn_ = this;
    val = eval('obj._fn_(' + args + ')' ) 
    delete obj._fn_;
    return val
}

bind

同样提供两种写法

Function.prototype.myBind = function(obj,...arg1){return (...arg2) => {let args = arg1.concat(arg2);
        let val ;
        obj._fn_ = this;
        val = obj._fn_(...args); 
        delete obj._fn_;
        return val
    }
}
Function.prototype.myBind = function(obj){
    let _this = this;
    let argArr = [];
    let arg1 = [];
    for(let i = 1 ; i<arguments.length ; i++){ // 从 1 开始 
        arg1.push(arguments[i] ); // 这里用 arg1 数组收集下参数
        // 获取 arguments 是从 1 开始, 但 arg1 要从 0(i-1) 开始
        // 若是用 Array.prototype.slice.call(argument) 就方便多了
        argArr.push('arg1[' + (i - 1)  + ']' ) ; // 如果用 arguments 在返回的函数里运行 会获取不到这个函数里的参数了
    }
    return function(){
        let val ;
        for(let i = 0 ; i<arguments.length ; i++){ // 从 0 开始
            argArr.push('arguments[' + i + ']' ) ;
        }
        obj._fn_ = _this;
        val = eval('obj._fn_(' + argArr + ')' ) ;
        delete obj._fn_;
        return val
    };
}

本文参考:
https://www.jianshu.com/p/9ce…
https://www.jianshu.com/p/3b6…

正文完
 0