我有一个 Atom
类(它代表物质宇宙中元素的原子):
class Atom {
constructor(neutronCount) {
this.neutronCount = neutronCount;
}
}
天然存在的元素有 92 种,例如氧就是其中之一。我想为每个元素创建一个子类。
class Oxygen extends Atom {
// By default, an oxygen atom has 8 neutrons but this can change.
// How can I define the subclass in such a way that Oxygen has
// 8 neutrons by default?
}
一个正常出现的氧原子默认中子数(8),但这可以改变,所以我希望能够创建一个像这样的原子:
var o = new Oxygen(); // creates Oxygen with 8 neutrons
var o9 = new Oxygen(9); // create Oxygen with 9 neutrons
如何以允许我输入可选参数(中子数)的方式定义氧气子类?如果我不输入参数,则采用默认值 8
?
最佳答案
class Oxygen extends Atom {
constructor(neutronCount = 8) {
// ---------------------^^^^
super(neutronCount);
}
}
这大致相当于:
class Oxygen extends Atom {
constructor(neutronCount) {
if (neutronCount === undefined) {
neutronCount = 8;
}
super(neutronCount);
}
}
因此 8
将用于 new Oxygen()
以及 new Oxygen(undefined)
。
如果您愿意,您甚至可以在调用 super
之前添加一些范围检查(如果有合理的范围可供应用)。我对分子物理学一无所知(或者是化学?),但例如,如果只有范围 5 <= x < 10 是合理的,那么:
class Oxygen extends Atom {
constructor(neutronCount = 8) {
if (neutronCount < 5 || neutronCount >= 10) {
throw new Error(`Oxygen cannot have a neutron count of ${neutronCount}`);
}
super(neutronCount);
}
}
关于javascript - 具有默认值的 JS 子类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56915634/