JavaScript 类与继承
学习 ES6 class 语法和面向对象编程 · 难度:进阶 · +15XP
JavaScript 类与继承
JavaScript 类与继承
学习前的准备
打开浏览器控制台(F12),并准备好你的代码编辑器。本教程面向已经了解 JavaScript 对象和函数基础的开发者。我们的目标是理解 ES6 引入的 class 语法——它是 JavaScript 中实现面向对象编程的核心机制。
什么是类?
在编程中,类就像一个“蓝图”或“模具”。你可以用这个模具来制造出一个个具体的对象(称为“实例”)。比如,“汽车”是一个类,而“你停在楼下那辆红色轿车”就是一个实例。类定义了对象应该有哪些属性(数据)和方法(行为)。
class Car {
constructor(brand, model) {
this.brand = brand;
this.model = model;
this.speed = 0;
}
accelerate(amount) {
this.speed += amount;
console.log(this.brand + this.model + ' 加速到 ' + this.speed + 'km/h');
}
brake() {
this.speed = 0;
console.log('停车了');
}
}
const myCar = new Car('丰田', '卡罗拉');
console.log(myCar.brand); // '丰田'
myCar.accelerate(50);
继承——让子类复用父类的功能
继承是面向对象编程的核心概念。子类通过 extends 关键字继承父类的所有属性和方法,然后可以添加自己的特化行为或覆盖父类的方法。
class Animal {
constructor(name) {
this.name = name;
}
speak() {
console.log(this.name + ' 发出声音');
}
}
class Dog extends Animal {
speak() {
console.log(this.name + ' 汪汪叫');
}
fetch() {
console.log(this.name + ' 去捡球了');
}
}
const dog = new Dog('旺财');
dog.speak(); // 旺财 汪汪叫
dog.fetch(); // 旺财 去捡球了
super 关键字
当子类有自己的构造函数时,必须先调用 super() 来执行父类的构造函数,然后才能使用 this。
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
introduce() {
console.log('我是' + this.name + ',' + this.age + '岁');
}
}
class Student extends Person {
constructor(name, age, grade) {
super(name, age);
this.grade = grade;
}
introduce() {
super.introduce();
console.log('我在' + this.grade + '年级');
}
}
const stu = new Student('小明', 15, '初三');
stu.introduce();
getter 和 setter
使用 get 和 set 关键字可以定义属性的读取和设置行为,让你在访问属性时执行额外的逻辑。
class Circle {
constructor(radius) {
this._radius = radius;
}
get area() {
return Math.PI * this._radius ** 2;
}
get diameter() {
return this._radius * 2;
}
set diameter(d) {
this._radius = d / 2;
}
}
const c = new Circle(5);
console.log(c.area); // 78.5398...
console.log(c.diameter); // 10
c.diameter = 20;
console.log(c._radius); // 10
小结
类帮助你用清晰的语法组织代码。constructor 初始化对象,extends 实现继承,super 调用父类。面向对象编程不仅仅是语法,更是一种思维方式——把复杂的系统分解为一个个相互协作的对象。建议你尝试用类来建模一个你熟悉的事物,比如“学生管理系统”或“图书借阅系统”。