模拟call实现

534 阅读1分钟
  1. 将函数设为对象的属性
  2. 执行&删除这个函数
  3. 指定this到函数并传入给定参数执行函数
  4. 如果不传入参数,默认指向window

    /**
    * 实现一个call方法
    */
    Function.prototype.myCall = function (context) {
        context = context ? Object(context) : window;
        context.fn = this; // 获取调用call的函数
        let args = [];
        for (let i = 1, len = arguments.length; i < len; i++) {        args.push(arguments[i]);    }
        let result = context.fn(...args);
        return result;    }
    
    var value = 'global';
    var foo = {
        value: 1
    };
    var bar = function (name, age) {
        console.log(this.value);
        return {
            value: this.value,
       name,
       age    }}
    bar.myCall(null);
    console.log(bar.myCall(foo, '铁拐李', 18));

参考资料

  1. www.cxymsg.com/guide/jsWri…

微信公众号“前端那些事儿”