在面向对象编程中,特别是在使用JavaScript这样的动态类型语言时,super
关键字用于调用父类(超类)的方法。当你在子类中重写一个方法,并且想要在该方法中调用父类的同名方法时,可以使用super
。
不可以。super
关键字只能用来调用父类中的原始方法,而不是别名。这是因为super
的工作方式是基于方法解析顺序(Method Resolution Order, MRO)的,它总是指向原始的方法定义。
假设我们有一个父类Parent
和一个子类Child
,在子类中我们想要调用父类的一个被别名的方法:
class Parent {
originalMethod() {
console.log('This is the original method.');
}
}
class Child extends Parent {
constructor() {
super();
this.aliasForOriginalMethod = this.originalMethod.bind(this);
}
// 尝试在子类中调用别名方法
callAlias() {
// 这里会报错,因为super不能调用别名方法
// super.aliasForOriginalMethod(); // 错误的用法
// 正确的用法是直接调用原始方法
super.originalMethod();
}
}
const childInstance = new Child();
childInstance.callAlias(); // 输出: This is the original method.
如果你需要在子类中调用父类的一个被别名的方法,你应该直接调用那个别名,而不是尝试使用super
来调用它。例如:
class Child extends Parent {
constructor() {
super();
this.aliasForOriginalMethod = this.originalMethod.bind(this);
}
callAlias() {
// 直接调用别名方法
this.aliasForOriginalMethod();
}
}
const childInstance = new Child();
childInstance.callAlias(); // 输出: This is the original method.
在这个例子中,我们通过this.aliasForOriginalMethod()
直接调用了别名方法,而不是尝试使用super
来调用它。
super
只能用来调用父类的原始方法。领取专属 10元无门槛券
手把手带您无忧上云