在 JavaScript 中,类继承是通过原型链实现的。ES6 引入了 class
和 extends
关键字,使得类继承更加清晰和易于理解。
class Parent {
constructor(name) {
this.name = name;
}
sayHello() {
console.log(`Hello, I'm ${this.name}`);
}
}
class Child extends Parent {
constructor(name, age) {
super(name); // 调用父类的constructor
this.age = age;
}
sayAge() {
console.log(`I'm ${this.age} years old`);
}
}
const child = new Child('Alice', 10);
child.sayHello(); // Hello, I'm Alice
child.sayAge(); // I'm 10 years old
extends
关键字:用于声明一个类继承另一个类super
关键字:super()
必须在使用 this
之前调用super
用于调用父类的方法子类可以重写父类的方法:
class Child extends Parent {
constructor(name, age) {
super(name);
this.age = age;
}
// 重写父类方法
sayHello() {
console.log(`Hi, I'm ${this.name} and I'm ${this.age} years old`);
}
}
const child = new Child('Bob', 8);
child.sayHello(); // Hi, I'm Bob and I'm 8 years old
静态方法也会被继承:
class Parent {
static staticMethod() {
console.log('Parent static method');
}
}
class Child extends Parent {}
Child.staticMethod(); // Parent static method
可以使用 instanceof
检查对象是否属于某个类或其父类:
console.log(child instanceof Child); // true
console.log(child instanceof Parent); // true
也可以继承 JavaScript 内置类型:
class MyArray extends Array {
first() {
return this[0];
}
last() {
return this[this.length - 1];
}
}
const arr = new MyArray(1, 2, 3);
console.log(arr.first()); // 1
console.log(arr.last()); // 3
super()
才能使用 this
super()
类继承提供了一种更清晰、更接近传统面向对象语言的方式来组织 JavaScript 代码。