JavaScript私有字段(#)是运行时强制的真正私有,TypeScript private仅是编译时检查,生成的JS中无保护,前者更安全后者用于开发约束。
JavaScript 的私有类字段和 TypeScript 的 private 修饰符虽然都用于实现类成员的“私有性”,但它们在机制、作用时机和运行时行为上有本质区别。
JavaScript 在 ES2025 正式引入了私有类字段,使用 # 前缀来定义。这种私有性是运行时强制执行的。
特点包括:
class Counter {
#count = 0;
increment() {
this.#count++;
}
getCount() {
return this.#count;
}
}
const c = new Counter();
c.#count; // SyntaxError: Private field '#count' must be declared in an enclosing class
TypeScript 的 private 是编译时的访问控制机制,属于类型系统的一部分。
关键点:
class Counter {
private
count = 0;
increment() {
this.count++;
}
getCount() {
return this.count;
}
}
const c = new Counter();
// c.count; // 编译错误:属性 'count' 是私有的
(c as any).count = 10; // 绕过类型检查,运行时可行
两者最核心的不同在于:
基本上就这些。如果你需要真正的私有状态,应优先使用 JavaScript 的 # 字段,尤其是在库开发中。TypeScript 的 private 更适合团队协作中的代码规范和开发体验。两者可以共存,但不要误以为 private 能阻止运行时访问。