extends实现js
使用 extends 实现 JavaScript 继承
在 JavaScript 中,extends 关键字用于实现类之间的继承。通过 extends,子类可以继承父类的属性和方法,同时可以扩展或重写父类的功能。
基本语法
class Parent {
constructor(name) {
this.name = name;
}
greet() {
console.log(`Hello, ${this.name}`);
}
}
class Child extends Parent {
constructor(name, age) {
super(name); // 调用父类的 constructor
this.age = age;
}
greet() {
super.greet(); // 调用父类的 greet 方法
console.log(`I am ${this.age} years old`);
}
}
const child = new Child('Alice', 10);
child.greet();
关键点
super关键字用于调用父类的构造函数或方法。- 子类的构造函数中必须先调用
super(),才能使用this。 - 子类可以重写父类的方法,同时通过
super保留父类的逻辑。
继承内置类
extends 也可以用于继承 JavaScript 的内置类,例如 Array 或 Error。
class CustomArray extends Array {
getFirstElement() {
return this[0];
}
}
const arr = new CustomArray(1, 2, 3);
console.log(arr.getFirstElement()); // 1
注意事项
- 如果子类没有定义
constructor,JavaScript 会自动调用父类的constructor。 - 静态方法也会被继承,可以通过
super调用父类的静态方法。
class Parent {
static staticMethod() {
console.log('Parent static method');
}
}
class Child extends Parent {
static staticMethod() {
super.staticMethod();
console.log('Child static method');
}
}
Child.staticMethod();






