如果我想在基类中定义一个常量,然后在子类中重写它,我该怎么办?
问题是,对于我的具体情况,这个常量是一个 new Map()
,并且将在构造函数期间查阅结果:
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"
}
}
SubCmd1
和 SubCmd2
都需要定义自己的 getMyMap()
版本,以便在 this 之前在基本构造函数中使用
可以访问。
getMyMap()
方法的格式为,
getMyMap() {
return new Map()
.set("name1", arg11, arg12)
.set("name2", arg21, arg22)
}
是否有可能以某种方式使其发挥作用? 您可以从-https://jsbin.com/xubijosuro/edit?js,console,output开始
PS。以下是我如何使用SubCmd1
、SubCmd2
等:
const cli = new CliCaseA(name, argsObj)
const usage = cli.Usage()
if (usage) { console.log(`Usage:\n\n${usage}`) process.exit() }
最佳答案
您正在寻找类(或 getter 或方法)的静态属性,您甚至可以在使用 new.target
调用 super()
之前访问该属性。 :
class MappedCmd extends Cmd {
constructor(name, arg1, arg2 = null) {
const myMap = new.target.getMyMap();
// ^^^^^^^^^^
…
super(name, arg1, arg2)
}
static getMyMap() {
return new Map(); // to be overridden or extended in the subclasses
}
}
关于javascript - ES6,在访问 'this'并在派生类中定义常量之前必须调用super,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54610784/