js extends 实现
extends 的基本用法
在 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); // 调用父类的构造函数
this.age = age;
}
greet() {
super.greet(); // 调用父类的方法
console.log(`I am ${this.age} years old`);
}
}
const child = new Child('Alice', 10);
child.greet();
super 关键字的作用
super 用于在子类中调用父类的构造函数或方法。必须在子类构造函数中使用 super() 后才能使用 this。
class Parent {
constructor(value) {
this.value = value;
}
}
class Child extends Parent {
constructor(value, extra) {
super(value); // 必须调用
this.extra = extra;
}
}
继承内置类型
extends 可以继承 JavaScript 内置类型,如 Array、Error 等。
class CustomArray extends Array {
isEmpty() {
return this.length === 0;
}
}
const arr = new CustomArray(1, 2, 3);
console.log(arr.isEmpty()); // false
静态方法的继承
静态方法也会被继承,可以通过 super 在子类中调用父类的静态方法。
class Parent {
static staticMethod() {
return 'Parent static';
}
}
class Child extends Parent {
static staticMethod() {
return super.staticMethod() + ' + Child static';
}
}
console.log(Child.staticMethod()); // "Parent static + Child static"
检查继承关系
使用 instanceof 可以检查对象的继承关系。

class Parent {}
class Child extends Parent {}
const child = new Child();
console.log(child instanceof Parent); // true
注意事项
- 子类必须在
constructor中调用super(),除非子类没有显式定义构造函数 - 箭头函数没有自己的
this,不能用作构造函数,也不能用extends继承 - 可以继承普通的构造函数(非 class),但有一些限制
function ParentFunc(name) {
this.name = name;
}
ParentFunc.prototype.greet = function() {
console.log(`Hello, ${this.name}`);
};
class Child extends ParentFunc {
constructor(name, age) {
super(name);
this.age = age;
}
}
const child = new Child('Bob', 12);
child.greet(); // "Hello, Bob"






