为什么私有静态字段不像私有实例字段那样被继承?

问题描述 投票:0回答:1

来自MDN文档

私有静态字段有一个限制:只有定义了私有静态字段的类才能访问该字段。使用

this
时,这可能会导致意外行为。在下面的示例中,当我们尝试调用
this
时,
BaseClassWithPrivateStaticField
指的是 SubClass 类(而不是
SubClass.basePublicStaticMethod()
类),因此会导致 TypeError。

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
javascript inheritance language-design static-members private-members
1个回答
0
投票

相反,私有实例字段是继承的

不,他们也不是。私有字段不是原型继承的,访问它们不遵循原型链。

静态字段和实例字段的区别是后者是由

constructor
创建的,是“继承”的,所以默认也是在子类实例上创建的(在
super()
调用中)。静态属性没有等效的功能,当子类
extends
它时,父类没有代码运行(并且可以创建私有静态字段)。

© www.soinside.com 2019 - 2024. All rights reserved.