类是 JavaScript 中实现面向对象编程的基础。ES6 引入了 class 语法,使得创建类和实现继承变得更加简单和直观。
使用 class 关键字可以定义一个类。
// 定义类class Person {// 构造函数constructor(name, age) {this.name = name;this.age = age;}// 方法sayHello() {console.log(`你好,我是${this.name},今年${this.age}岁`);}}// 创建实例const person = new Person('张三', 25);person.sayHello(); // 你好,我是张三,今年25岁
类可以包含属性和方法。属性是类的数据,方法是类的行为。
实例属性和方法属于类的实例,每个实例都有自己的副本。
class Car {constructor(brand, model) {// 实例属性this.brand = brand;this.model = model;this.speed = 0;}// 实例方法accelerate() {this.speed += 10;console.log(`${this.brand} ${this.model} 加速到 ${this.speed} km/h`);}brake() {this.speed = Math.max(0, this.speed - 10);console.log(`${this.brand} ${this.model} 减速到 ${this.speed} km/h`);}}const myCar = new Car('丰田', '卡罗拉');myCar.accelerate(); // 丰田 卡罗拉 加速到 10 km/hmyCar.accelerate(); // 丰田 卡罗拉 加速到 20 km/hmyCar.brake(); // 丰田 卡罗拉 减速到 10 km/h
静态属性和方法属于类本身,而不是类的实例。它们通过类名访问,而不是通过实例访问。
class MathUtils {// 静态属性static PI = 3.14159;// 静态方法static square(x) {return x * x;}static cube(x) {return x * x * x;}}console.log(MathUtils.PI); // 3.14159console.log(MathUtils.square(5)); // 25console.log(MathUtils.cube(3)); // 27
ES2022 引入了私有属性和方法,使用 # 前缀表示。
class BankAccount {#balance = 0; // 私有属性constructor(initialBalance) {this.#balance = initialBalance;}// 私有方法#validateAmount(amount) {return amount > 0;}deposit(amount) {if (this.#validateAmount(amount)) {this.#balance += amount;console.log(`存款成功,当前余额: ${this.#balance}`);} else {console.log('存款金额必须大于0');}}withdraw(amount) {if (this.#validateAmount(amount) && amount <= this.#balance) {this.#balance -= amount;console.log(`取款成功,当前余额: ${this.#balance}`);} else {console.log('取款金额必须大于0且不超过余额');}}getBalance() {return this.#balance;}}const account = new BankAccount(1000);account.deposit(500); // 存款成功,当前余额: 1500account.withdraw(200); // 取款成功,当前余额: 1300console.log(account.getBalance()); // 1300// console.log(account.#balance); // 错误:私有属性无法从外部访问
类可以通过 extends 关键字实现继承,子类可以继承父类的属性和方法。
// 父类class Animal {constructor(name) {this.name = name;}speak() {console.log(`${this.name} 发出声音`);}}// 子类class Dog extends Animal {constructor(name, breed) {super(name); // 调用父类构造函数this.breed = breed;}// 重写父类方法speak() {console.log(`${this.name} 汪汪叫`);}// 子类特有方法fetch() {console.log(`${this.name} 在接飞盘`);}}const dog = new Dog('旺财', '柴犬');dog.speak(); // 旺财 汪汪叫dog.fetch(); // 旺财 在接飞盘
子类可以重写父类的方法,提供自己的实现。
class Shape {constructor(color) {this.color = color;}getArea() {return 0;}getPerimeter() {return 0;}describe() {console.log(`这是一个${this.color}的图形`);}}class Circle extends Shape {constructor(color, radius) {super(color);this.radius = radius;}getArea() {return Math.PI * this.radius * this.radius;}getPerimeter() {return 2 * Math.PI * this.radius;}describe() {super.describe(); // 调用父类方法console.log(`这是一个半径为 ${this.radius} 的圆`);}}const circle = new Circle('红色', 5);circle.describe(); // 这是一个红色的图形 \n 这是一个半径为 5 的圆console.log(`面积: ${circle.getArea().toFixed(2)}`); // 面积: 78.54console.log(`周长: ${circle.getPerimeter().toFixed(2)}`); // 周长: 31.42
下面是一个简单的任务管理系统,你可以尝试完成以下任务:
Task
类,包含标题、描述、截止日期和完成状态属性TaskList
类来管理多个任务