实现call

 Function.prototype _call(context) {
        // 只有函数才能调用
        if (typeof this !== "function") {
          throw new TypeError("error");
        }
        // 如果没有指定this默认指向window
        context = context || window;
        // 将arguments转为数组
        const args = [];
        for (let i = 1; i <= arguments.length; i++) {
          args.push(arguments[i]);
        }
        // 将symbol作为键以免重复
        const fn = Symbol();
        context[fn] = this;
        // 使用Spread语法传参也可以 context[fn](...args)
        const ret = eval("context[fn](" + args + ")");
        delete context[fn];
        return ret;
      }

实现apply

 Function.prototype._apply = function (context = window, arg) {
        if (typeof this !== "function") {
          throw new TypeError("error");
        }
        const fn = Symbol();
        context[fn] = this;
        context[fn](arg);
        delete context[fn];
        return res;
      };

实现bind

 Function.prototype._bind = function (thisArg = window, ...args) {
        if (typeof this !== "function") {
          throw new TypeError("error");
        }
        const fn = Symbol();
        thisArg[fn] = this;
        const _this = this;
        // bind调用后返回一个函数
        return function bindFn(...params) {
        // 此处判断是否被new调用
          if (this instanceof bindFn) {
            return new _this(...args, ...params);
          } else {
            const res = thisArg[fn](...args, ...params);
            delete thisArg[fn];
            return res;
          }
        };
      };

Kev1n
5 声望2 粉丝