javascript - 具有默认值的 JS 子类

标签 javascript subclass

我有一个 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

最佳答案

使用 default parameter value :

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/

相关文章:

javascript - Lodash groupBy 带有 React 的胖箭头函数

javascript - 当 Event.stopPropagation 不起作用时,如何防止在祖先元素上注册相同的事件?

javascript 中的 php var

python - 惯用地将 BaseClass 对象转换为 SubClass 对象?

swift - 从未出现在 View 中的子类创建按钮

javascript - 发送短信后回调到html页面

javascript - 从最后一次迭代开始的嵌套 for 循环的复杂性

ios - 子类未找到父类(super class)接口(interface)的 Objective-c 错误

python - 了解 JSONEncoder 的子类化

windows - 如何在 Windows 中子类化一个窗口? (使用围棋)