TypeScript 中有 三种访问修饰符:
修饰符 | 作用 |
---|---|
public |
默认修饰符,类的 内部和外部 都可以访问 |
protected |
类内部和子类 可以访问,但外部不能访问 |
private |
只有类内部 可以访问,子类和外部都不能访问 |
class Person {
public name: string; // 公开,任何地方都能访问
protected age: number; // 受保护,子类可以访问
private password: string; // 私有,只有本类能访问
constructor(name: string, age: number, password: string) {
this.name = name;
this.age = age;
this.password = password;
}
public getName(): string {
return this.name; // ✅ public 方法可以访问 public 成员
}
protected getAge(): number {
return this.age; // ✅ protected 方法可以访问 protected 成员
}
private getPassword(): string {
return this.password; // ✅ private 方法只能在本类中访问
}
}
class Employee extends Person {
constructor(name: string, age: number, password: string) {
super(name, age, password);
}
displayInfo(): void {
console.log(`Name: ${this.name}`); // ✅ public,可以访问
console.log(`Age: ${this.age}`); // ✅ protected,子类可以访问
// console.log(`Password: ${this.password}`); ❌ private,子类不能访问
}
}
const emp = new Employee("John", 30, "1234");
console.log(emp.name); // ✅ public,外部可以访问
// console.log(emp.age); // ❌ protected,外部不能访问
// console.log(emp.password); // ❌ private,外部不能访问
OOP(Object-Oriented Programming,面向对象编程)是一种代码组织方式,通过对象(Object)和类(Class)来组织代码,使代码更易维护、更可复用、更结构化。
在 JavaScript/TypeScript 里,OOP 主要依靠**类(Class)和对象(Object)**来实现。
原则 | 作用 |
---|---|
封装(Encapsulation) | 把数据和方法封装在对象内部,保护数据不被外部直接修改 |
继承(Inheritance) | 让一个类继承另一个类的功能,代码复用 |
多态(Polymorphism) | 让子类能覆盖父类的方法,增强扩展性 |
抽象(Abstraction) | 只暴露必要的信息,隐藏实现细节 |
封装 = 保护数据 + 提供方法访问数据
问题: 不能让别人直接修改你的银行余额,只能通过“存款/取款”方法修改。
class BankAccount {
private balance: number; // 🔒 私有变量,外部不能直接访问
constructor(initialBalance: number) {
this.balance = initialBalance;
}
// ✅ 提供方法来访问和修改数据
deposit(amount: number) {
if (amount > 0) {
this.balance += amount;
console.log(`存款成功,当前余额:$${this.balance}`);
}
}
withdraw(amount: number) {
if (amount > this.balance) {
console.log("❌ 余额不足!");
} else {
this.balance -= amount;
console.log(`取款成功,当前余额:$${this.balance}`);
}
}
getBalance() {
return this.balance;
}
}
// 使用对象
const myAccount = new BankAccount(100);
myAccount.deposit(50); // 存款成功,当前余额:$150
myAccount.withdraw(30); // 取款成功,当前余额:$120
console.log(myAccount.getBalance()); // 120
// ❌ 直接访问 balance(会报错)
// console.log(myAccount.balance);
✅ 封装的好处:
balance
,避免了数据篡改deposit()
和 withdraw()
控制余额的更新,保证安全性继承 = 代码复用,让子类继承父类的功能