数组call方法的基本实现

41 阅读1分钟
         Function.prototype.myCall = function (curThis) {
        //判断调用的是否是函数
        if (typeof this !== "function") {
          throw new Error();
        }
        //判断传入的第一个参数,
        if (curThis === null || curThis === undefined) {
          curThis = window;
        }
        //判断基本数据类型,改成包装类
        switch (typeof curThis) {
          case "number":
            curThis = new Number(curThis);
            break;
          case "string":
            curThis = new String(curThis);
            break;
          case "boolean":
            curThis = new Boolean(curThis);
            break;
          default:
            curThis = curThis;
            break;
        }
        //实现
        curThis.func = this;
        const test = curThis.func(...[...arguments].slice(1));
        delete curThis.func;
        return test;
      };
      function fn(a) {
        console.log(a);
        console.log(this);
      }
      fn.call([]);
      fn.myCall([]);