原文链接: js class 中 成员函数和箭头函数的注意点
下一篇: vscode 多设备 单独同步设置的方法
参考
自动bind成员函数
https://github.com/andreypopp/autobind-decorator
1, 箭头函数会被babel编译到constructor里面作为this.xxx = xxx 使用, 导致原型链失效
2, 不能再子类中使用super调用父类中的箭头函数
3, 性能上箭头函数最差, 因为无法在原型中找到, 并且每个实例都含有一个该函数的拷贝
4, 尽量使用bind代替箭头函数
下面是两组对比, 成员函数 > bind > 箭头函数
<!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>