Appearance
十三、Class 类(面向对象)
ES6 引入了 Class 语法,使 JavaScript 的面向对象编程更加清晰和规范。Class 是基于原型继承的语法糖,提供了更接近传统面向对象语言的写法。
类的定义
javascript
// ES6 类定义
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
greet() {
console.log(`Hello, my name is ${this.name}!`);
}
getAge() {
return this.age;
}
}
// 创建实例
const person = new Person('John', 30);
console.log(person.name); // John
console.log(person.getAge()); // 30
person.greet(); // Hello, my name is John!constructor 构造函数
constructor 方法是类的构造函数,在创建实例时自动调用。
javascript
class Car {
constructor(make, model, year) {
this.make = make;
this.model = model;
this.year = year;
this.mileage = 0;
}
drive(distance) {
this.mileage += distance;
console.log(`Drove ${distance} miles. Total mileage: ${this.mileage}`);
}
}
const car = new Car('Toyota', 'Camry', 2023);
console.log(car.make); // Toyota
console.log(car.mileage); // 0
car.drive(100); // Drove 100 miles. Total mileage: 100方法定义
类中的方法定义不需要使用 function 关键字。
javascript
class Calculator {
add(a, b) {
return a + b;
}
subtract(a, b) {
return a - b;
}
multiply(a, b) {
return a * b;
}
divide(a, b) {
if (b === 0) {
return 'Cannot divide by zero';
}
return a / b;
}
}
const calculator = new Calculator();
console.log(calculator.add(5, 3)); // 8
console.log(calculator.subtract(5, 3)); // 2
console.log(calculator.multiply(5, 3)); // 15
console.log(calculator.divide(6, 3)); // 2继承 extends / super
使用 extends 关键字实现类的继承,super 关键字调用父类的构造函数或方法。
javascript
// 父类
class Animal {
constructor(name) {
this.name = name;
}
speak() {
console.log(`${this.name} makes a sound`);
}
}
// 子类
class Dog extends Animal {
constructor(name, breed) {
// 调用父类的构造函数
super(name);
this.breed = breed;
}
// 重写父类方法
speak() {
console.log(`${this.name} barks`);
}
getBreed() {
return this.breed;
}
}
const dog = new Dog('Buddy', 'Labrador');
dog.speak(); // Buddy barks
console.log(dog.getBreed()); // Labrador
const animal = new Animal('Generic animal');
animal.speak(); // Generic animal makes a sound静态方法 static
使用 static 关键字定义静态方法,静态方法属于类本身,而不是实例。
javascript
class MathUtils {
// 静态方法
static add(a, b) {
return a + b;
}
static multiply(a, b) {
return a * b;
}
// 实例方法
calculateArea(radius) {
return Math.PI * radius * radius;
}
}
// 调用静态方法
console.log(MathUtils.add(5, 3)); // 8
console.log(MathUtils.multiply(5, 3)); // 15
// 调用实例方法
const math = new MathUtils();
console.log(math.calculateArea(5)); // 78.53981633974483实战:创建实例对象
javascript
// 定义类
class User {
constructor(id, name, email) {
this.id = id;
this.name = name;
this.email = email;
this.createdAt = new Date();
}
getUserInfo() {
return {
id: this.id,
name: this.name,
email: this.email,
createdAt: this.createdAt
};
}
updateEmail(newEmail) {
this.email = newEmail;
console.log(`Email updated to ${newEmail}`);
}
}
// 创建用户实例
const user1 = new User(1, 'John Doe', 'john@example.com');
const user2 = new User(2, 'Jane Smith', 'jane@example.com');
// 使用实例方法
console.log(user1.getUserInfo());
user1.updateEmail('john.doe@example.com');
console.log(user1.getUserInfo());
console.log(user2.getUserInfo());Class 的优势
- 代码清晰:类的结构更加清晰,易于理解
- 继承简单:使用 extends 关键字实现继承,更加直观
- 方法定义简洁:不需要 function 关键字
- 与传统 OOP 一致:语法更接近传统面向对象语言
- 静态方法:支持静态方法,方便定义工具函数
注意事项
- Class 是语法糖:底层仍然是基于原型继承
- 严格模式:类内部默认使用严格模式
- constructor 方法:如果没有定义 constructor,会默认添加一个空的 constructor
- this 指向:在类方法中,this 指向实例
通过本章节的学习,你已经掌握了 ES6 中 Class 的基本用法。Class 语法使 JavaScript 的面向对象编程更加规范和清晰,是现代 JavaScript 开发的重要特性。
