手写 call apply bind

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>call&apply&bind</title>
  </head>
  <body>
    <script>
      // 将方法挂载到对象上
      // 执行对象的方法
      // 将这个方法从对象上移除
      Function.prototype.myCall = function (context, ...args) {
        let fn = Symbol(1);
        context[fn] = this;
        context[fn](...args);
        Reflect.deleteProperty(context, 'fn');
      };
      Function.prototype.myApply = function (context, args = []) {
        let fn = Symbol(1);
        if (args && !(args instanceof Array)) {
          throw 'error';
        }
        context[fn] = this;
        context[fn](...args);
        Reflect.deleteProperty(context, 'fn');
      };
      Function.prototype.myBind = function (context, ...args) {
        return (...args2) => {
          let fn = Symbol(1);
          context[fn] = this;
          context[fn](...args.concat(...args2));
          Reflect.deleteProperty(context, 'fn');
        };
      };
    </script>
  </body>
</html>

 

posted @ 2022-05-09 22:20  苹果π  阅读(27)  评论(0编辑  收藏  举报