1. 公共类型(public)

  • 作用:默认访问修饰符,允许在类内部、子类和外部任意访问。

  • APIpublic member: type

  • 用法

class Person {
  public name: string; // 显式声明
  age: number;        // 默认 public(隐式)

  constructor(name: string, age: number) {
    this.name = name;
    this.age = age;
  }
}

const p = new Person("Alice", 30);
console.log(p.name); // 外部直接访问 ✅
  • 用处

    • 暴露类的外部接口

    • 实现跨类/模块的数据共享

    • 作为基类供子类继承的公共成员

2. 私有类型(private)

  • 作用:仅限类内部访问,外部和子类均不可访问。

  • APIprivate member: type

  • 用法

class BankAccount {
  private balance: number; // 私有属性

  constructor(initial: number) {
    this.balance = initial;
  }

  // 通过公共方法间接访问私有成员
  public withdraw(amount: number): void {
    if (amount <= this.balance) {
      this.balance -= amount; // ✅ 类内部可访问
    }
  }
}

const acc = new BankAccount(1000);
console.log(acc.balance); // ❌ 编译错误:属性“balance”为私有属性
  • 用处

    • 封装敏感数据(如密码、金额)

    • 防止外部直接修改内部状态

    • 隐藏复杂实现细节

外部访问方法:

使用 Getter/Setter 方法(推荐):

class BankAccount {
  private _balance: number;

  constructor(initial: number) {
    this._balance = initial;
  }

  // Getter 方法用于读取余额
  public get balance(): number {
    return this._balance;
  }

  // 可以添加 Setter 方法(如果需要外部修改)
  public set balance(amount: number) {
    if (amount >= 0) {
      this._balance = amount;
    } else {
      throw new Error("余额不能为负数");
    }
  }

  public withdraw(amount: number): void {
    if (amount <= this._balance) {
      this._balance -= amount;
    } else {
      throw new Error("余额不足");
    }
  }

  public deposit(amount: number): void {
    if (amount > 0) {
      this._balance += amount;
    } else {
      throw new Error("存款金额必须大于0");
    }
  }
}

// 使用示例
const acc = new BankAccount(1000);
console.log(acc.balance); // ✅ 通过 getter 访问:1000

acc.withdraw(200);
console.log(acc.balance); // ✅ 800

acc.deposit(500);
console.log(acc.balance); // ✅ 1300

// 如果需要直接设置余额(谨慎使用)
acc.balance = 2000;
console.log(acc.balance); // ✅ 2000

3. 静态类型(static)

  • 作用:属于类本身而非实例,通过类名直接访问。

  • APIstatic member: typestatic method() {...}

  • 用法

class MathUtils {
  static PI: number = 3.14;          // 静态属性
  static sum(a: number, b: number): number {  // 静态方法
    return a + b;
  }
}

// 无需实例化,直接通过类名访问
console.log(MathUtils.PI);            // 3.14
console.log(MathUtils.sum(2, 3));     // 5
  • 用处

    • 存储全局常量(如配置项)

    • 实现工具函数(无需实例上下文)

    • 实现单例模式(结合私有构造函数)

关键区别总结

特性 公共类型(public) 私有类型(private) 静态类型(static)
访问范围 类内/子类/外部 仅限类内部 通过类名直接访问
存储位置 实例属性 实例属性 类本身(非实例)
典型用途 公开 API、跨类数据共享 封装敏感数据、隐藏实现细节 工具方法、全局常量
继承行为 子类可继承并覆盖 子类不可访问 子类可继承
内存分配 每个实例独立存储 每个实例独立存储 全类共享单份内存

使用场景对比

  • 公共成员:构建类的外部契约(如 class Button { public onClick() {...} }

  • 私有成员:保护内部状态(如 class Cache { private data: Map<...> }

  • 静态成员

    • 常量:static DEFAULT_CONFIG = {...}

    • 工厂方法:static create() { return new MyClass() }

    • 计数器:static instanceCount = 0

最佳实践

  1. 最小暴露原则:优先用 private,仅在必要时使用 public

  2. 避免滥用 static:过度使用会导致代码耦合和测试困难

  3. 单例模式示例

class AppConfig {
  private static instance: AppConfig;
  private constructor() {} // 私有构造函数

  public static getInstance(): AppConfig {
    if (!AppConfig.instance) {
      AppConfig.instance = new AppConfig();
    }
    return AppConfig.instance;
  }
}
const config = AppConfig.getInstance(); // 全局唯一实例

Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐