类与继承
约 227 字小于 1 分钟
布欧-Lewyon
2026-05-16
首页 › JavaScript › ES6+ 深入 › 类与继承
class 语法
class Animal {
constructor(name) {
this.name = name;
}
speak() {
console.log(`${this.name} 发出声音`);
}
// 静态方法
static description() {
return '所有动物的基类';
}
}
const dog = new Animal('狗');
dog.speak();
console.log(Animal.description());继承 extends
class Dog extends Animal {
constructor(name, breed) {
super(name); // 必须先调用 super
this.breed = breed;
}
speak() {
super.speak(); // 调用父类方法
console.log(`${this.name} 汪汪叫`);
}
static description() {
return `${super.description()} → 狗类`;
}
}
class Cat extends Animal {
speak() {
console.log(`${this.name} 喵喵叫`);
}
}私有字段
class BankAccount {
#balance = 0; // 私有字段(ES2022)
deposit(amount) {
this.#balance += amount;
}
getBalance() {
return this.#balance;
}
}
const acc = new BankAccount();
// acc.#balance; // ❌ 私有字段,外部不可访问
acc.deposit(100);
console.log(acc.getBalance()); // 100小结
| 语法 | 作用 |
|---|---|
class | 定义类 |
constructor | 构造函数 |
extends | 继承 |
super() | 调用父类构造函数 |
static | 静态方法 |
#field | 私有字段 |
