封装
一句话解释
封装是 练习的 bundling 数据 and 方法那个操作 on 它 together, 虽然 hiding 内部 details.
用大白话说
Encapsulation means putting data and the functions that work on that data into one unit (like a class or object), and hiding the internal details from the outside. The outside world can only interact through a controlled interface (public methods).
想象一个 car: you use the steering wheel and pedals (the interface), but you do not need to know how the engine works internally (the encapsulated details). If the manufacturer changes the engine, you still steer the same way.
Encapsulation benefits: (1) it simplifies usage — you use the interface without understanding internals, (2) it protects data — internal state cannot be corrupted by external code, (3) it enables change — you can rewrite internals without breaking callers. In JavaScript, closures and private fields (#field) provide encapsulation.
示例
class BankAccount {
#balance = 0; // private field
deposit(amount) {
if (amount > 0) this.#balance += amount;
}
getBalance() {
return this.#balance;
}
}
const account = new BankAccount();
account.deposit(100);
console.log(account.getBalance()); // 100
// account.#balance = 999; // Error — cannot access private field#balance 字段是 私有 — 它能 仅是 修改通过 deposit 方法. 外部 code cannot directly 设置 or 读取它, protecting 数据从 无效状态.
相关术语
相关资源
相关课程
- Programming Paradigms
学习关于 OOP 概念.
解读错误信息
用大白话解释常见错误——什么意思、为什么发生、如何修复。