javascript - 构造函数在 JavaScript 类中是强制性的吗?

标签 javascript ecmascript-6

我正在从 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 中的类声明/表达式中是否是必需的。

最佳答案

你应该只写一个没有构造函数的类,看看它是否有效:)

来自same docs

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/

相关文章:

javascript - 我可以根据单选按钮状态设置图像样式吗?

javascript - 覆盖 JS 中的获取方法并转发 Promises

javascript - 遍历数组时应该使用 for-of 还是 forEach?

ecmascript-6 - 无法导出 const 箭头函数

javascript - 在 ES6 中格式化日期

javascript - Chrome 自动填充输入 - 有事件吗?

javascript - 安装 Express.js 后更改 node.js 项目名称

javascript - 使用 onclick 函数更改变量

javascript - 巴别塔 : The CLI has been moved into the package `babel-cli`

javascript - 如何找到下一个数组元素的值?