现代JavaScript_私有字段与方法

JavaScript在ES2025中引入了私有字段和方法,使用#前缀实现类成员的真正私有性,仅可在类内部访问,外部无法读取或修改,支持实例与静态成员,增强了封装性。

JavaScript 在 ES2025 引入了类的私有字段和方法,让开发者能更自然地实现封装。以前我们只能通过约定(如以下划线 _ 开头表示“私有”)或闭包来模拟私有成员,现在可以通过语法层面真正实现私有性。

私有字段(Private Fields)

私有字段使用井号 # 作为前缀声明,只能在类的内部访问,外部无法读取或修改。

例如:

class BankAccount {
  #balance = 0;

  constructor(initialBalance) {
    if (initialBalance > 0) {
      this.#balance = initialBalance;
    }
  }

  deposit(amount) {
    if (amount > 0) {
      this.#balance += amount;
    }
  }

  getBalance() {
    return this.#balance;
  }
}

const account = new BankAccount(100);
account.deposit(50);
console.log(account.getBalance()); // 150
// console.log(account.#balance); // SyntaxError: Cannot access private field

上面的 #balance 是私有字段,只能在 BankAccount 内部使用。尝试从外部访问会报错。

私有方法(Private Methods)

同样,私有方法也用 # 前缀定义,可用于封装内部逻辑。

例如:

class PasswordValidator {
  #minLength = 8;
  #hasSpecialChar(password) {
    return /[!@#$%^&*]/.test(password);
  }

  #hasEnoughLength(password) {
    return password.length >= this.#minLength;
  }

  validate(password) {
    return (
      this.#hasEnoughLength(password) &&
      this.#hasSpecialChar(password)
    );
  }
}

const validator = new PasswordValidator();
console.log(validator.validate("hello!123")); // true
// validator.#hasSpecialChar("test"); // Error

这里 #hasSpecialChar#hasEnoughLength 是私有方法,仅用于内部验证流程,不暴露给使用者。

静态私有字段与方法

私有性也适用于静态成员。静态私有字段和方法同样以 # 开头,只能在类内部调用。

示例:

class Logger {
  static #logCount = 0;
  static #maxLogs = 5;

  static #canLog() {
    return Logger.#logCount   }

  static log(message) {
    if (this.#canLog()) {
      console.log(message);
      Logger.#logCount++;
    } else {
      console.warn("Log limit reached");
    }
  }
}

Logger.log("First"); // 输出
Logger.log("Second");
// ...最多输出5次
// Logger.#logCount; // 错误:无法访问

静态私有成员适合管理类级别的状态或工具逻辑,同时防止被外部篡改。

基本上就这些。私有字段和方法让 JavaScript 类更接近传统面向对象语言的封装能力,写大型应用时更安全、清晰。