Javascript。什么时候必须在子 类 声明中使用构造函数?

Javascript. When do I have to use constructor in child classes declaration?

我想知道我做的是否正确...

有这个代码:

class Room {
 constructor(type, size, hasWindows, equipment) {
    this.type       = type;
    this.size       = size;
    this.hasWindows = hasWindows;
    this.equipment  = ['esterillas', ...equipment];
 };
};  

class PilatesRoom extends Room {

};

const room1 = new PilatesRoom('pilates', 20, true, ['balón medicinal'])
console.log(room1);
//returns: PilatesRoom {type: "pilates", size: 20, hasWindows: true, equipment: Array(2)}

我的意思是...我真的不需要使用 "constructor" 和 "super" 来使其完美运行,但是当我在互联网上查看时,每个人都在使用它。我是不是该?例如:

class PilatesRoom extends Room {
 constructor(type, size, hasWindows, equipment) {
  super(type, size, hasWindows, equipment)
 };
};

这个returns一样

我正在努力理解!谢谢你们的宝贵时间。

当您想使用 child class 的构造函数时,您必须使用 super() 表达式。否则你不必。就这么简单。

class PilatesRoom extends Room {
 // the constructor should be removed (there is no point to keep it):
 constructor(type, size, hasWindows, equipment) { 
  super(type, size, hasWindows, equipment)
 };
};

在上面的代码中,没有理由定义构造函数。但是在下面的代码中你必须调用 foo() 因此你也必须使用 super():

class PilatesRoom extends Room {
 constructor(type, size, hasWindows, equipment) {
  super(type, size, hasWindows, equipment)
  foo()
 };
};

更多信息在这里:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/super#Description

如果不添加任何逻辑,则不必添加子 class 构造函数。 (事实上​​ ,静态分析和代码质量工具有时会将其标记为 "useless constructor" 并发出警告。)

有些程序员更喜欢构造函数的显式定义,有些可能会继承其他可能需要它的语言的习惯,等等。但是除非子构造函数实际上为子构造函数做了一些事情 class 而不仅仅是将相同的值传递给父构造函数,这是没有必要的。

代码越少越好。因此,如果您的 child class 没有附加属性并且不需要特殊的初始化逻辑,请跳过它。如果你跳过它,你会得到默认的构造函数,这已经足够了。

您需要维护每一行代码。没有线路就没有维护。

据我所知class构造函数只是javascript中的一个语法糖,所以你不必使用它。

同样如 MDN 解释:

"The constructor method is a special method for creating and initializing an object created with a class. There can only be one special method with the name "constructor" in a class。如果 class 包含多次出现的构造方法,将抛出 SyntaxError。

构造函数可以使用super关键字调用superclass的构造函数。

正如它所提到的,它可以存在也可以不存在。

MDN for further understanding