js class 中 成员函数和箭头函数的注意点

原文链接: js class 中 成员函数和箭头函数的注意点

上一篇: ts-toolbelt Boolean 模块

下一篇: vscode 多设备 单独同步设置的方法

参考

https://medium.com/@charpeni/arrow-functions-in-class-properties-might-not-be-as-great-as-we-think-3b3551c440b1

自动bind成员函数

https://github.com/andreypopp/autobind-decorator

1, 箭头函数会被babel编译到constructor里面作为this.xxx = xxx 使用, 导致原型链失效

2, 不能再子类中使用super调用父类中的箭头函数

3, 性能上箭头函数最差, 因为无法在原型中找到, 并且每个实例都含有一个该函数的拷贝

4, 尽量使用bind代替箭头函数

下面是两组对比, 成员函数 > bind > 箭头函数

up-0554529f7fb5fe3dd9372fdc2585a203007.png

up-c8d6a93895bf0568a27460b835ecdbcb100.png

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <script>
      class People {
        constructor(id) {
          this.id = id;
        }
        p1() {
          console.log("p1:", this.id);
        }
        p2 = () => {
          console.log("p2:", this.id);
        };
      }
      class Stu extends People {
        constructor(id, name) {
          super(id);
          this.name = name;
        }

        f1() {
          console.log("f1:", this.id, this.name);
        }
        f2 = () => {
          console.log("f2:", this.id, this.name);
        };

        f3() {
          super.p1();
        }
        f4() {
          super.p2();
        }
        f5(f) {
          setTimeout(() => {
            console.log("f5:", this.id, this.name);
          });
        }
      }

      const s = new Stu("123", "abc");
      console.log(s);
      s.f1();
      s.f2();
      s.f3();
    //   s.f4();
      s.f5();
    </script>
  </body>
</html>

up-c729f89f3a09bd6fda8f6b847e3544033aa.png

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值