ES6, Must call super before accessing 'this' and defining constant in derived class

一曲冷凌霜 提交于 2021-01-29 07:53:16

问题


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() }

回答1:


You are looking for a static property of the class (or getter or method) that you can access even before the super() call using new.target:

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
  }
}


来源:https://stackoverflow.com/questions/54610784/es6-must-call-super-before-accessing-this-and-defining-constant-in-derived-cl

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!