Calling grand-parent function in javascript

I get this class inheritance structure:

class GrandParent{
  funcA(){
    console.log('GrandParent');
  }
}
class Parent extends GrandParent{
  funcA(){
    console.log('Parent');
  }
}
class Child extends Parent{
  funcA(){
    console.log('Child');
    // how to call funcA of GrandParent -> super.super.funcA()
  }
}

Question is: how can I call GrandParent.funcA() from Child.funcA()?

Child

GrandParent

Should be logged on console.

Thanks;

Answers:

Answer

You can call it via new GrandParent().funcA();

class GrandParent {
  funcA() {
    console.log('GrandParent');
  }
}
class Parent extends GrandParent {
  funcA() {
    console.log('Parent');
  }
}
class Child extends Parent {
  funcA() {
    console.log('Child');
    new GrandParent().funcA();
  }
}

const child = new Child();
child.funcA();

Answer

This is contradictory: you've overriden GranParent.funcA with a new implementation. If you need what GranParent.funcA does, probably you'll need to decompose your code a bit, and override Child.funcA as needed depending on your actual use case.

Take advantage of polymorphism:

class GrandParent {
  doStuff() {
    console.log('some stuff')
  }

  funcA() {
    this.doStuff()
    console.log('GrandParent')
  }
}

class Parent extends GrandParent {
  funcA() {
    console.log('Parent')
  }
}

class Child extends Parent {
  funcA() {
    this.doStuff()
    console.log('child')
  }
}

const child = new Child()
child.funcA()

Answer

If you want to get the function using the super keyword. You need to call the super in parent function to point the funcA in class Grandparent.

class GrandParent{
  funcA(){
    console.log('GrandParent');
  }
}
class Parent extends GrandParent{
  funcA(){
    console.log('Parent');
    super.funcA();
  }
}
class Child extends Parent{
  funcA(){
    console.log('Child');
    super.funcA();

  }
}

var x = new Child();
x.funcA();

Answer

If you actually want to use super keyword it's possible, but you'll need to point to appropriate prototype. In other words you should go through __proto__ object chain manually.

class Level1 {
  me() { console.log('Level1'); }
}

class Level2 extends Level1 {
  me() { console.log('Level2'); }
}

class Level3 extends Level2 {
  me() { 
    super.__proto__.__proto__.__proto__.me();
    //      ^         ^         ^ reference to Level1 prototype
    //      |         | reference to Level2 prototype 
    //      | reference to Level3 prototype
    console.log('Level3'); 
  }
}

const foo = new Level3();
foo.me();

But as it's said before, probably it worth to rethink the logic to avoid such structure in your code.

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.