在类中通过哈希前缀#标记的字段都将被私有,子类实例将无法继承
例如
class ClassWithPrivateField {
#privateField;
#privateMethod() {
return 'hello world';
}
constructor() {
this.#privateField = 42;
}
}
const instance = new ClassWithPrivateField()
console.log(instance.privateField); //undefined
console.log(instance.privateMethod); //undefined
可以看到,属性privateField和方法privateMethod都被私有化了,在实例中无法获取到
网友评论