JavaScript 类中可以定义多个构造函数吗?
不是完全正确。在一个类中,可以定义多个构造函数,但这些构造函数必须拥有不同的参数列表。这种定义多个构造函数的方式叫做构造函数重载。例如:
class Person {
constructor(name) {
this.name = name;
}
constructor(name, age) {
this.name = name;
this.age = age;
}
}
上面的代码就定义了两个构造函数,分别接收不同的参数。但是这段代码是错误的,因为 JavaScript 不支持构造函数重载。
正确的做法是使用默认参数:
class Person {
constructor(name, age = null) {
this.name = name;
this.age = age;
}
}
这样就只有一个构造函数,但是可以接收不同数量的参数。
原文地址: https://www.cveoy.top/t/topic/oJ3A 著作权归作者所有。请勿转载和采集!