0

The following works.

class Parent {
    constructor(x) {
        this.x = x;
    }
    
    present() {
        return `I have a ${this.x}`;
    }
}


class Child extends Parent {
    constructor(x, y) {
        super(x);
        this.y = y;
    }

    // different name !!!
    show() {
        return `${this.present()}, it is a ${this.y}`;
    }
}


child = new Child("Tinggu", "Winggu");
console.log(child.present());

However, unlike in Java, methods in the Parent and Child class with the same name don't seem to work.

...

class Child extends Parent {
    constructor(x, y) {
        super(x);
        this.y = y;
    }

    // same name !!!
    present() {
        return `${this.present()}, it is a ${this.y}`;
    }
}

...

Is there anyway to make this work?

Grateful
  • 9,685
  • 10
  • 45
  • 77

1 Answers1

2

To invoke the method of a parent with the same name, use super:

    present() {
        return `${super.present()}, it is a ${this.y}`;
    }
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
  • Aaah. Silly mistake! Got it thanks. But in that case, what would be the way to invoke the parent method from the child object? `child = new Child("Tinggu", "Winggu"); console.log(child.present()); // <-- this only invokes the child class` – Grateful Jul 30 '20 at 05:50
  • That's not possible and that's probably a good thing. Code that uses `Child` shouldn't really make any assumptions about its implementation. – Felix Kling Jul 30 '20 at 06:43
  • Actually... It IS possible. I found this out here. https://stackoverflow.com/questions/63167043/how-can-we-invoke-the-parents-method-when-a-child-has-a-method-with-the-same-n – Grateful Jul 30 '20 at 06:50
  • I mean... sure. You can also do `Object.getPrototypeOf(Object.getPrototpyeOf(child)).present.call(child)`. But neither of these approaches change the fact that the caller now makes assumptions about `child`'s implementation, which is not great. If you think you have to do this then it might be worth taking a step back and change the architecture/composition of the classes. – Felix Kling Jul 30 '20 at 07:43