JavaScript 快速入门

类(Class)

类是 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/h
myCar.accelerate(); // 丰田 卡罗拉 加速到 20 km/h
myCar.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.14159
console.log(MathUtils.square(5)); // 25
console.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); // 存款成功,当前余额: 1500
account.withdraw(200); // 取款成功,当前余额: 1300
console.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.54
console.log(`周长: ${circle.getPerimeter().toFixed(2)}`); // 周长: 31.42

动手试试

下面是一个简单的任务管理系统,你可以尝试完成以下任务:

  1. 创建一个 Task 类,包含标题、描述、截止日期和完成状态属性
  2. 添加方法来标记任务为已完成
  3. 创建一个 TaskList 类来管理多个任务
  4. 实现添加、删除和查找任务的功能
  5. 添加一个方法来获取所有未完成的任务
Made by 捣鼓键盘的小麦 / © 2025 Front Study 版权所有