箭头函数有没有 super
javascript 中的箭头函数没有 super。因为箭头函数不绑定自己的 this、arguments、super 或 new.target,所以它在语法上不支持使用 super 关键字。

为什么普通方法可以用 super 而箭头函数不行
普通方法可以使用 super 是因为它们属于类定义的一部分,并且具有动态的 this 绑定,能够访问原型链上的父类方法。而箭头函数是在定义时就捕获了词法作用域内的 this,它无法像普通方法那样根据调用上下文动态改变 this 的值,因此也就无法支持 super 这种依赖于动态 this 的特性。

class Parent {
constructor() {
this.name = "Parent";
}
greet() {
return `Hello from ${this.name}`;
}
}
class Child extends Parent {
constructor() {
super();
this.name = "Child";
}
// 普通方法:可以使用 super
normalGreet() {
return super.greet(); // 正确,输出 "Hello from Child"
}
// 箭头函数:不能使用 super
arrowGreet = () => {
// return super.greet(); // 错误!SyntaxError: 'super' keyword unexpected here
};
}
const child = new Child();
console.log(child.normalGreet()); // 输出: Hello from Child
// console.log(child.arrowGreet()); // 如果取消注释并修复 super 问题,会报错
立即学习“Java免费学习笔记(深入)”;
在什么情况下你会尝试在箭头函数中使用 super
开发者通常会在需要将回调函数绑定到当前实例时尝试在箭头函数中使用 super,例如在事件处理或异步操作中。然而,由于箭头函数本身不支持 super,你需要通过其他方式来实现类似的功能,比如使用普通方法或者将 super 的结果存储在变量中供箭头函数使用。
class Parent {
getValue() {
return 42;
}
}
class Child extends Parent {
constructor() {
super();
this.value = null;
}
setupCallback() {
// 存储 super 调用的结果
const parentValue = super.getValue();
// 箭头函数可以使用闭包访问 parentValue
setTimeout(() => {
console.log(`Parent value is: ${parentValue}`); // 输出: Parent value is: 42
}, 100);
}
}
const child = new Child();
child.setupCallback();


















