在JavaScript中,重写父类的方法是通过原型链来实现的。当你在子类中定义了一个与父类同名的方法时,子类的方法就会覆盖父类的方法。这种方式被称为方法的重写(Override)。
基础概念:
new
关键字一起使用。super
关键字:在子类中,可以使用super
关键字来调用父类的构造函数或方法。优势:
类型:
应用场景:
示例代码:
// 父类
class Animal {
constructor(name) {
this.name = name;
}
speak() {
console.log(`${this.name} makes a noise.`);
}
}
// 子类
class Dog extends Animal {
constructor(name) {
super(name); // 调用父类的构造函数
}
// 重写父类的speak方法
speak() {
console.log(`${this.name} barks.`);
}
}
const animal = new Animal('Generic Animal');
animal.speak(); // 输出: Generic Animal makes a noise.
const dog = new Dog('Rex');
dog.speak(); // 输出: Rex barks.
遇到的问题及解决方法:
super
关键字来初始化父类的属性,可能会导致this
未定义的错误。解决方法是确保在子类的构造函数中调用super
。super.methodName()
来调用父类的方法。在重写方法时,应该注意以下几点:
super
关键字来访问父类的方法,以便在子类中扩展而不是完全替换父类的行为。this
的上下文,在构造函数中使用super
之前,this
是不可用的。领取专属 10元无门槛券
手把手带您无忧上云