来自MDN文档:
私有静态字段有一个限制:只有定义了私有静态字段的类才能访问该字段。使用
时,这可能会导致意外行为。在下面的示例中,当我们尝试调用this
时,this
指的是 SubClass 类(而不是BaseClassWithPrivateStaticField
类),因此会导致 TypeError。SubClass.basePublicStaticMethod()
class BaseClassWithPrivateStaticField { static #PRIVATE_STATIC_FIELD; static basePublicStaticMethod() { return this.#PRIVATE_STATIC_FIELD; } } class SubClass extends BaseClassWithPrivateStaticField {} SubClass.basePublicStaticMethod(); // TypeError: Cannot read private member #PRIVATE_STATIC_FIELD from an object whose class did not declare it
[…]
建议您始终通过类名访问静态私有字段,而不是通过
,因此继承不会破坏方法。this
因此私有静态字段不会被继承,这会阻止在静态方法中使用
this
。 继承限制有什么好处?
相反,私有实例字段是继承的,这允许在实例方法中使用
this
:
class BaseClassWithPrivateInstanceField {
#PRIVATE_INSTANCE_FIELD;
basePublicInstanceMethod() {
return this.#PRIVATE_INSTANCE_FIELD;
}
}
class SubClass extends BaseClassWithPrivateInstanceField {}
new SubClass().basePublicInstanceMethod(); // undefined
相反,私有实例字段是继承的
不,他们也不是。私有字段不是原型继承的,访问它们不遵循原型链。
静态字段和实例字段的区别是后者是由
constructor
创建的,是“继承”的,所以默认也是在子类实例上创建的(在super()
调用中)。静态属性没有等效的功能,当子类extends
它时,父类没有代码运行(并且可以创建私有静态字段)。