If I want to define a constant in base class, then override it in sub-classes, how should I do?
The catch is that, for my specific case, this constant is a new Map()
, and the result will be consulted with during constructor:
class Cmd0 {
constructor(name, arg1, arg2 = null) {
this.name = name;
this.arg1 = arg1;
this.arg2 = arg2;
}
. . .
}
class Cmd extends Cmd0 {
constructor(name, arg1, arg2 = null) {
myMap = Somehow.getMyMap() // defined in sub-classes
if (!myMap.has(name)) { super(null, null, null); return } // fail the constructor
super(name, arg1, arg2)
}
}
class SubCmd1 extends Cmd {
Usage() {
if (this.name) return null
else return "cmd sub1 bla bla bla"
}
}
class SubCmd2 extends Cmd {
Usage() {
if (this.name) return null
else return "cmd sub2 bla bla bla"
}
}
Both SubCmd1
and SubCmd2
need to define their own version of getMyMap()
to be consumed in base constructor, before this
can be accessed.
The getMyMap()
method would be in the format of,
getMyMap() {
return new Map()
.set("name1", arg11, arg12)
.set("name2", arg21, arg22)
}
Is it possible to somehow make it work? You can start from - https://jsbin.com/xubijosuro/edit?js,console,output
PS. Here is how I'm using SubCmd1
, SubCmd2
, etc:
const cli = new CliCaseA(name, argsObj)
const usage = cli.Usage()
if (usage) { console.log(`Usage:\n\n${usage}`) process.exit() }