在JavaScript中,类中的构造函数是必需的吗? [英] In JavaScript, is constructor mandatory in a class?

查看:144
本文介绍了在JavaScript中,类中的构造函数是必需的吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读 Mozilla文档部分的JavaScript类。 '类主体和方法定义'。在构造函数部分下,它声明

I am reading about JavaScript class from the Mozilla documentation section of 'Class body and method definitions'. Under the Constructor section, it states that


构造函数方法是一种用于创建和初始化使用类创建的对象的特殊方法。在类中只能有一个名为constructor的特殊方法。如果类包含多个构造函数方法,则将抛出SyntaxError。
构造函数可以使用super关键字来调用超类的构造函数。

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

From the statement above, I can confirm that we can't have more than one constructor. But it does not mention whether a constructor is mandatory in a class declaration/expression in JavaScript.

推荐答案

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

You should have just write a class without constructor and see it works or not :)

来自 相同的文档


如上所述,如果未指定构造函数方法,则使用默认构造函数。对于基类,默认构造函数是:

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中,类中的构造函数是必需的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆