我正在从 Mozilla documentation section of 'Class body and method definitions' 阅读有关 JavaScript 类的信息.在 Constructor 部分下,它指出
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. A SyntaxError will be thrown if the class contains more than one occurrence of a constructor method. A constructor can use the super keyword to call the constructor of the super class.
从上面的陈述中,我可以确认我们不能有多个构造函数。但是它没有提到构造函数在 JavaScript 中的类声明/表达式中是否是必需的。
最佳答案
你应该只写一个没有构造函数的类,看看它是否有效:)
As stated, if you do not specify a constructor method a default constructor is used. For base classes the default constructor is:
constructor() {}
For derived classes, the default constructor is:
constructor(...args) {
super(...args);
}
关于javascript - 构造函数在 JavaScript 类中是强制性的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48657481/