JavaScript OOP:从蓝图到现实
Source: Dev.to

介绍
到目前为止,你可能一直在过程式地编写代码——写一行,然后再写一行,再再写一行。这就像把食谱写在一张随手的纸片上。但当你想要开设一个全球连锁餐厅时会怎样?你不能依赖纸片。你需要一个 系统。
在 JavaScript 中,面向对象编程(OOP) 就是那个系统。它让我们能够把代码模型化为现实世界。
1. 大构想:蓝图 vs. 现实
理解面向对象编程的最佳方式是 汽车工厂 类比。
- 蓝图(类): 定义每辆车必须有4个轮子、颜色和发动机。它还说明车辆可以“Drive”和“Brake”。
- 实际的汽车(对象/实例): 从装配线下来后的实体汽车。可能是一辆红色的 Tesla,也可能是一辆蓝色的 Ford。两者遵循相同的蓝图,但都是独立的 对象。
2. JavaScript 中的类是什么?
class 是 JavaScript 中的保留关键字(在 ES6 中引入),它充当创建对象的模板。它将数据(属性)和行为(方法)组合在一起。
在没有类之前,代码可能会变得凌乱:
let student1Name = "Veer";
let student1Age = 20;
let student2Name = "Ansh";
let student2Age = 22;
// This gets messy fast!3. “构造函数”:设置阶段
每个类都可以定义一个名为 constructor 的特殊方法。可以把它看作在创建新对象时运行的 装配线。
创建学生蓝图
class Student {
// The constructor is the 'Setup' function
constructor(name, age, course) {
this.name = name; // 'this' refers to the specific student being built
this.age = age;
this.course = course;
}
// This is a method (action)
introduce() {
console.log(`Hi, I'm ${this.name}, a ${this.age}-year-old studying ${this.course}.`);
}
}为什么使用 this?
在类内部,this 指向正在创建的特定实例,使每个对象能够存储自己的数据。
4. 创建对象:new 关键字
要从蓝图创建实际对象,请使用 new 关键字。此过程称为 实例化。
// 从同一蓝图制造两个独特的学生
const student1 = new Student("Veer", 20, "Web Dev");
const student2 = new Student("Ansh", 22, "Data Science");
// 它们拥有相同的“行为”
student1.introduce(); // Hi, I'm Veer...
student2.introduce(); // Hi, I'm Ansh...5. 封装的力量
封装——面向对象四大支柱之一——意味着将复杂的逻辑隐藏在类内部。程序的其余部分只需了解方法 做什么,而不必关心它 如何 实现。
- 更有条理: 所有与 “Student” 相关的代码都集中在一个地方。
- 更易调试: 如果
introduce()出错,你只需检查这一处。 - 可复用: 只需几行代码即可创建成千上万的学生。
6. 过程式 vs. 面向对象 风格
| Feature | Procedural (Old Way) | OOP (The Modern Way) |
|---|---|---|
| Logic | Functions and data are separate. | Data and logic are bundled together. |
| Scaling | Hard to manage as the app grows. | Designed for large, complex apps. |
| Analogy | A list of instructions. | A collection of interacting “things.” |
7. Summary Challenge: Build Your Library
在控制台中尝试以下操作:
- 创建一个名为
Book的类。 - 添加一个构造函数,接受
title、author和year。 - 添加一个名为
getAge的方法,返回当前年份 - year。 - 创建两个对象(你最喜欢的书)。
- 记录 两个对象调用
.getAge()的结果。
class Book {
constructor(title, author, year) {
this.title = title;
this.author = author;
this.year = year;
}
getAge() {
const currentYear = new Date().getFullYear();
return currentYear - this.year;
}
}
// Example usage
const book1 = new Book("1984", "George Orwell", 1949);
const book2 = new Book("The Pragmatic Programmer", "Andrew Hunt & David Thomas", 1999);
console.log(`${book1.title} is ${book1.getAge()} years old.`);
console.log(`${book2.title} is ${book2.getAge()} years old.`);最终思考
面向对象编程不仅仅是语法;它是一种 mindset。它鼓励你把代码视为相互交互的对象世界,而不是线性的任务列表。掌握它,你就能构建任何东西——从简单的待办事项应用到庞大的社交媒体平台。