关于javascript:优雅的实现callapplybind

38次阅读

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

实现 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;
          }
        };
      };

正文完
 0