Search code examples
javascriptnode.jsclasssuperclass

How a super function can access another super function inside a child class?


//parent class
module.exports = class Parser {
    constructor() {}
    tokenize(s) {}
    fixDates(rule) {}

}


//child class
const Parser = require('./parser');
module.exports = class ParserEn extends Parser {
    constructor() {}

    run(str) {
        super.tokenize(str.toLowerCase()).forEach(function (s) {

            //here i want to acces to another function in the parent class
            super.fixDates(rule); //I get this error: 'super' keyword unexpected here
        });
    }
}

Hi, As you can see in the above code, I have two functions in the parent class and a function in the child class. In the run function inside the child class, I can access to the to the tokenize by using keyword "super". However, I need to access the fixDates function too, but I do get this error: "'super' keyword unexpected here" . Would be great if someone helps me. Thanks in advance


Solution

  • You need to call super() in the constructor of the child class. You should also use an arrow function in the forEach callback, to preserve the this context:

    class Parser {
      constructor() {}
      tokenize(s) { return [...s]; }
      fixDates(rule) { console.log(rule); }
    }
    
    class ParserEn extends Parser {
      constructor() {
        super();
      }
      run(str) {
        super.tokenize(str.toLowerCase()).forEach((s) => {
          super.fixDates(s);
        });
      }
    }
    
    const parseren = new ParserEn();
    parseren.run('foo');