Javascript:为什么在子类中声明属性会覆盖父类中与null相同的属性 [英] Javascript: Why does declaring a property in a subclass overwrite the same property in a super class as null
问题描述
我的问题与理解类如何为属性分配值以及如何在Javascript中实例化对象有关.我想了解更多此过程的工作原理.
My question has to do with understanding how classes assign values to properties and how objects are instantiated in Javascript. I would like to understand more how this process works.
如果我创建两个类,其中第二个类继承自第一个类
If I create two classes where the second inherits from the first
class A {
name
constructor(name){
this.name = name
}
}
class B extends A {
name
status
constructor(name, status){
super(name)
this.status = status
}
}
然后在我将其打印到控制台时创建类B的实例
And then create an instance of class B, when I print it to the console
x = new B('myClass', true)
console.log(x)
它显示名称变量未定义
B { name: undefined, status: true }
我很确定B中的name属性会覆盖A中的name属性,但是为什么A构造函数不将新的name变量分配为传递给它的值?
I'm pretty sure that the name property in B is over-writing the name property in A, but why doesn't the A constructor assign the new name variable to be the value passed into it?
推荐答案
目前(2020年10月),这是正确的行为.
This is correct behaviour for the moment (October 2020).
设置时
class A {
name
}
这将声明一个 class字段.它还不是标准,它是第3阶段的提案.它可能会改变,但变化不大.第三阶段是候选阶段,可能包括精修阶段.
This declares a class field. It's not a standard yet, it's a proposal in stage 3. It's likely to change but not by much. Stage 3 is the candidate stage and might include finishing refinements.
无论如何,根据提案的当前规范,您所看到的都是正确的.没有初始化程序的所有类字段都设置为 undefined
.发生这种情况是因为您在 B
中有另一个名为 name
的类字段,而没有初始化程序.在父构造函数中发生的分配将被覆盖.
At any rate, what you are seeing is correct according to the current spec of the proposal. Any class fields without initialisers are set to undefined
. This happens because you have another class field called name
in B
without an initialiser. The assignment that happens in the parent constructor will be overwritten.