gpt4 book ai didi

Javascript:为什么在子类中声明属性会覆盖父类(super class)中的相同属性为null

转载 作者:行者123 更新时间:2023-12-03 06:59:29 24 4
gpt4 key购买 nike

我的问题与理解类如何为属性赋值以及对象如何在 Javascript 中实例化有关。我想更多地了解这个过程是如何工作的。
如果我创建两个类,其中第二个继承自第一个

class A {
name

constructor(name){
this.name = name
}
}

class B extends A {
name
status

constructor(name, status){
super(name)
this.status = status
}
}
然后创建一个B类的实例,当我将它打印到控制台时
x = new B('myClass', true)
console.log(x)
它打印名称变量未定义
B { name: undefined, status: true }
我很确定 B 中的 name 属性覆盖了 A 中的 name 属性,但是为什么 A 构造函数不将新的 name 变量分配给传递给它的值?

最佳答案

这是目前(2020 年 10 月)的正确行为。
当你设置

class A {
name
}
这声明了一个类字段。它还不是标准,它是 a proposal in stage 3 .它可能会改变,但不会改变太多。第 3 阶段是候选阶段,可能包括完成改进。
无论如何,根据提案的当前规范,您所看到的都是正确的。任何没有初始化器的类字段都设置为 undefined .发生这种情况是因为您有另一个名为 name 的类字段。在 B没有初始化程序。在父构造函数中发生的赋值将被覆盖。
Here is the relevant part of the proposal that discusses this behaviour :

Fields without initializers are set to undefined

Both public and private field declarations create a field in the instance, whether or not there's an initializer present. If there's no initializer, the field is set to undefined. This differs a bit from certain transpiler implementations, which would just entirely ignore a field declaration which has no initializer.

For example, in the following example, new D would result in an object whose y property is undefined, not 1.

class C {
y = 1;
}
class D extends C {
y;
}

The semantics of setting fields without initializers to undefined as opposed to erasing them is that field declarations give a reliable basis to ensure that properties are present on objects that are created. This helps programmers keep objects in the same general state, which can make it easy to reason about and, sometimes, more optimizable in implementations.

关于Javascript:为什么在子类中声明属性会覆盖父类(super class)中的相同属性为null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64357900/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com