apply call bind手写实现

apply call bind手写实现


javascript 手写实现 函数绑定
<!DOCTYPE html>
<html>
  <head>
    <title>Call&Apply&Bind</title>
    <script type="text/javascript">
      //手写call apply bind
      Function.prototype.mycall = function (obj, ...args) {
        const context = obj;
        const fn = Symbol();

        context[fn] = this;

        let res = context[fn](...args);

        delete context[fn];

        return res;
      };

      Function.prototype.myapply = function (obj, args) {
        const context = obj;
        const fn = Symbol();

        context[fn] = this;

        let res = context[fn](...args);

        delete context[fn];

        return res;
      };

      Function.prototype.mybind = function (obj, ...args) {
        const self = this;
        return function () {
          return self.myapply(obj, args);
        };
      };

      function toSum(a, b) {
        return this.num + a + b;
      }

      let tmp = { num: 100 };

      console.log(toSum.mycall(tmp, 1, 2)); //103
      console.log(toSum.myapply(tmp, [1, 2])); //103
      console.log(toSum.mybind(tmp, 1, 2)()); //103
    </script>
  </head>
  <body></body>
</html>
© 2025 Niko Xie