在 javascript 中,使用 class 私有字段(以 # 开头)时,子类无法直接访问父类的私有字段。若需实现继承并共享状态,应改用受保护的实例属性(无 # 前缀),或在父类中提供 getter/setter 方法供子类调用。

为什么子类不能访问父类的私有字段
因为私有字段是绑定到具体类定义上的,而非实例本身。每个 class 声明会创建一个新的私有命名空间,子类和父类属于不同的类作用域,因此互相不可见。

class Parent {
#secret = "I am private";
getSecret() { return this.#secret; }
}
class Child extends Parent {}
const c = new Child();
console.log(c.getSecret()); // "I am private"
// console.log(c.#secret); // SyntaxError: Private field '#secret' must be declared in an enclosing class
上述代码验证了:虽然 #secret 是私有的,但通过父类暴露的方法 getSecret(),子类实例仍可间接读取其值。而直接访问会抛出语法错误。
如何设计可继承的状态结构
将需要被子类使用的状态定义为普通实例属性(无前缀),并在构造函数中初始化。这样子类可通过 super() 或原型链正常访问和修改这些属性。
使用Atmosphere构建通过WebSocket、SSE、gRPC、WebTransport、MCP、A2A和AG-UI流传输的JVM代理网关,并带有治理钩子。

class Parent {
constructor(name) {
this.name = name; // 非私有,可被继承访问
}
greet() {
return `Hello, ${this.name}`;
}
}
class Child extends Parent {
constructor(name, age) {
super(name);
this.age = age;
}
introduce() {
return `${this.greet()}, I am ${this.age} years old.`;
}
}
const child = new Child("Alice", 5);
console.log(child.introduce()); // "Hello, Alice, I am 5 years old."
该示例展示了标准继承模式:name 作为公共属性被 Child 继承并使用,greet() 方法也可被子类调用。这种设计避免了私有字段的访问限制问题,同时保持逻辑清晰。
当必须隐藏内部状态时如何处理
如果确实需要隐藏某些数据,但不希望完全阻断继承,可在父类中封装一个方法,由子类通过该方法操作内部状态。例如,提供一个 updateSecret() 方法,允许子类在特定条件下修改私有字段。
class Parent {
#secret = "default";
getSecret() { return this.#secret; }
setSecret(value) { this.#secret = value; }
}
class Child extends Parent {
resetSecret() {
this.setSecret("reset by child");
}
}
const c = new Child();
console.log(c.getSecret()); // "default"
c.resetSecret();
console.log(c.getSecret()); // "reset by child"
此方案中,#secret 仍为私有,但通过 setSecret() 提供了可控的写入通道。子类 Child 可以调用该方法来改变状态,既保持了封装性,又支持了继承行为。
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南










