1

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

    present() {
        return `${super.present()}, it is a ${this.y}`;
    }
}


child = new Child("Tinggu", "Winggu");
console.log(child.present()); // invokes the child version

How would I invoke the parent's method, from the child object? Type-Casting like Java doesn't seem to help.

Grateful
  • 9,685
  • 10
  • 45
  • 77
  • 1
    Do you mean `present()` instead of `parent()` in the `Child` class ? – Hao Wu Jul 30 '20 at 06:04
  • 3
    Does this answer your question? [How to call a parent method from child class in javascript?](https://stackoverflow.com/questions/11854958/how-to-call-a-parent-method-from-child-class-in-javascript) – Tim VN Jul 30 '20 at 06:05
  • @TimVN NO... it doesn't help me! Sorry. – Grateful Jul 30 '20 at 06:09
  • You are not or you don't want to? `Parent.prototype.present.call(this)` would achieve what you want. – Tim VN Jul 30 '20 at 06:17
  • @TimVN The `prototype` concept is completely foreign to me. So I did not understand the link that you provided. – Grateful Jul 30 '20 at 06:18
  • However, when presented properly to a newbie... It does begin to make sense. Just like @adiga did below. Much appreciated. – Grateful Jul 30 '20 at 06:19
  • 1
    Understandable. Check out this link to get a better understanding of this concept: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Inheritance_and_the_prototype_chain – Tim VN Jul 30 '20 at 06:20
  • Much appreciated. – Grateful Jul 30 '20 at 06:20

1 Answers1

2

The methods inside the class get added to Parent.prototype. So, you could call the Parent's present function with the child object as this

Parent.prototype.present.call(child)

Here's a snippet:

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

    present() {
        return `${super.present()}, it is a ${this.y}`;
    }
}

const child = new Child("Tinggu", "Winggu");
console.log(
  Parent.prototype.present.call(child)
);
adiga
  • 34,372
  • 9
  • 61
  • 83
  • Not sure why this was downvoted... also worth pointing out that if this needs to be done frequently, you can `const present = Parent.prototype.present.call.bind(Parent.prototype.present); present(child);` – Patrick Roberts Jul 30 '20 at 06:14
  • However, this concept of `prototype` is completely new to me. Can you pint me to any introductory articles on the internet that will help me understand this better? – Grateful Jul 30 '20 at 06:16
  • 1
    @Grateful https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Objects/Object_prototypes – Patrick Roberts Jul 30 '20 at 06:18