关于手写代码的收集及实现

42 阅读1分钟

手写 bind

    Function.prototype.myBind = function (ctx, ...args) {
        // 参数归一化  将传入的this归一化为 全局对象或对象
        ctx = ctx === undefined || ctx === null ? globalThis : Object(ctx);
        // 定义唯一的key
        const key = Symbol();
        // 在传入的this上挂载唯一函数
        ctx[key] = this;
        // 返回一个函数
        return function F(...args2) {
          // 执行唯一函数
          const r = ctx[key](...args, ...args2);
          // 删除挂载的函数
          delete ctx[key];
          return r;
        };
      };
      const person = {
        name: "小明",
      };

      const methods = function (a, b) {
        console.log("[ this ] >", this);
        return a + b;
      };

      const res = methods.myBind(person, 1, 2)();
      console.log("[ res ] >", res);

手写 apply

Function.prototype.myApply = function (ctx, args) {
        // 判断方法调用第二个参数是否是数组
        if (Array.isArray(args)) {
          // 参数归一化  将传入的this归一化为 全局对象或对象
          ctx = ctx === undefined || ctx === null ? globalThis : Object(ctx);
          // 定义唯一的key
          const key = Symbol();
          // 在传入的this上挂载唯一函数
          ctx[key] = this;
          // 执行唯一函数
          const r = ctx[key](...args);
          // 删除挂载的函数
          delete ctx[key];
          return r;
        } else {
          throw new Error("myApply方法第二个参数必须为数组类型");
        }
      };

      const person = {
        name: "小明",
      };

      function methods(a, b) {
        return a + b;
      }

      const res = methods.myApply(person, [1, 2]);
      console.log("[ res ] >", res);
    </script>