dee cheok
dee cheok

Reputation: 257

call function at extends constructor

class PathController {
  constructor(){

  }

  getMainPage(){
    alert("getMainPage");
  }

  setPushState(){
    alert("setPushState");
  }
}

class MainMenu extends PathController {
  constructor (){
    // call my PathController here
    super();
    getMainPage();
    setPushState();
  }
}

let aMainMenu = new MainMenu();

my intention is to call my getMainPage and setPushState at my MainMenu constructor , i tired this.getMainPage and this.setPushState and it is not working as well. can anyone tell me how to call it ?

Upvotes: 0

Views: 40

Answers (2)

guest271314
guest271314

Reputation: 1

One approach would be to pass property names to super() which call the functions at PathController parent constructor

class PathController {
  constructor(fromMainMenu, ...props) {
    if (fromMainMenu) {
      for (let fn of props) {
         this[fn]()
      }
    }
  }

  getMainPage(){
    alert("getMainPage");
  }

  setPushState(){
    alert("setPushState");
  }
}

class MainMenu extends PathController {
  constructor () {
    // call my PathController here
    super(true, "getMainPage", "setPushState");
  }
}

let aMainMenu = new MainMenu();

Upvotes: 0

Tony Tai Nguyen
Tony Tai Nguyen

Reputation: 1653

Your super is your "this" since we are currently in the constructor. Here's how it should look:

class PathController {
  constructor(){

  }

  getMainPage(){
    alert("getMainPage");
  }

  setPushState(){
    alert("setPushState");
  }
}

class MainMenu extends PathController {
  constructor (){
    // call my PathController here
    super();
    super.getMainPage();
    super.setPushState();
  }
}

let aMainMenu = new MainMenu();

However once you are outside of the constructor, then you would use "this.getMainPage();"

Upvotes: 1

Related Questions