javascript 中 class 语法的私有方法通过 # 前缀标识符实现,这是语言层面的原生支持。在类定义内部使用 #methodname() 声明的方法只能在类实例上通过 this.#methodname() 调用,外部无法访问。这种机制确保了方法的真正私有性,避免了传统闭包或命名约定(如 _method)带来的安全隐患。

如何正确声明和调用私有方法
要声明一个私有方法,只需在方法名前面加上 # 符号。调用时必须在类的实例方法中使用 this 指向该私有方法。如果尝试从类外部访问,或者在静态方法中直接引用(除非是静态私有方法),都会抛出错误。

class Calculator {
// 声明私有方法
#add(a, b) {
return a + b;
}
#subtract(a, b) {
return a - b;
}
// 公共方法调用私有方法
calculate(operation, x, y) {
if (operation === 'add') {
return this.#add(x, y);
} else if (operation === 'subtract') {
return this.#subtract(x, y);
}
throw new Error('Unknown operation');
}
}
const calc = new Calculator();
console.log(calc.calculate('add', 5, 3)); // 输出: 8
// console.log(calc.#add(5, 3)); // SyntaxError: Private field '#add' must be declared in an enclosing class上述代码展示了 Calculator 类中两个私有方法 #add 和 #subtract 的定义与调用。公共方法 calculate 根据传入的操作类型分发到对应的私有方法。外部实例 calc 只能调用 calculate,无法直接访问私有方法。
立即学习“Java免费学习笔记(深入)”;
一个基于源码的 OpenAI Agents SDK JavaScript 和 TypeScript 技术文档。涵盖了代理编排、工具、转接、追踪以及实际安装路径。
私有方法与静态私有方法的区别
除了实例私有方法,JavaScript 还支持静态私有方法,它们属于类本身而非实例。静态私有方法同样使用 # 前缀,但通常在类级别定义,并通过 ClassName.#methodName() 或类内部的静态方法调用。它们不能通过实例访问,也不能被继承覆盖。

class Logger {
static #logCount = 0;
static #incrementLog() {
this.#logCount++;
}
static log(message) {
this.#incrementLog();
console.log(`[${this.#logCount}] ${message}`);
}
static getLogCount() {
return this.#logCount;
}
}
Logger.log('Start');
Logger.log('Process');
console.log(Logger.getLogCount()); // 输出: 2
// Logger.#incrementLog(); // TypeError: Cannot access private member '#incrementLog'在 Logger 类中,#logCount 是一个静态私有字段,#incrementLog 是静态私有方法。公共静态方法 log 和 getLogCount 可以访问这些私有成员。外部代码无法直接修改日志计数或调用增量方法,保证了状态的一致性。
私有方法在子类中的可见性限制
当子类继承包含私有方法的父类时,子类无法直接访问父类的私有方法。这是因为私有方法的作用域严格限制在定义它们的类块内,不包括任何子类。如果需要复用逻辑,应使用受保护的方法(通常以 _ 开头作为约定)或提取为独立的工具函数。
class Base {
#secret() {
return 'hidden';
}
publicMethod() {
return this.#secret();
}
}
class Derived extends Base {
// 无法访问 this.#secret()
// 必须通过父类的公共方法间接获取
derivedMethod() {
return this.publicMethod();
}
}
const d = new Derived();
console.log(d.derivedMethod()); // 输出: hidden
// console.log(d.#secret()); // SyntaxError这段代码验证了 Derived 类无法直接调用 Base 的私有方法 #secret。它只能通过 publicMethod 间接获取结果。这体现了私有方法在继承体系中的隔离特性,有助于封装实现细节。

















