简体   繁体   中英

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM