extends实现js
在 JavaScript 中实现继承的 extends 关键字
JavaScript 中的 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 关键字用于调用父类的构造函数或方法。在子类的 constructor 中,super 必须在 this 之前调用。

继承内置类型
extends 也可以用于继承 JavaScript 内置类型,如 Array、Error 等:
class CustomArray extends Array {
getFirst() {
return this[0];
}
getLast() {
return this[this.length - 1];
}
}
const arr = new CustomArray(1, 2, 3);
console.log(arr.getFirst()); // 1
console.log(arr.getLast()); // 3
静态方法的继承
静态方法也会被继承:
class Parent {
static staticMethod() {
console.log('Parent static method');
}
}
class Child extends Parent {}
Child.staticMethod(); // "Parent static method"
使用注意事项
- 如果子类没有定义
constructor,JavaScript 会自动生成一个并调用super() - 不能继承普通的构造函数(非
class定义的),需要使用Object.setPrototypeOf等方式 - 可以通过
instanceof检查继承关系:child instanceof Parent会返回true






