Hexanix
Hexanix

Reputation: 77

Javascript: Using super to call parent prototype function inside child prototype function

I have a question about prototypes and the usage of super in JS.

I have a parent class Person. I have hooked a new toString() function to Person.prototype .

Then, I have a child class Teacher (extends Person). I am trying to override the toString() method on its prototype too, however I would like to reuse the result of the toString() method of its parent.

I attempted to call the toString() method of the super object in the Teacher function, but I get an error saying that super is undefined. Why is that? Is it possible to reuse a method of the parent through super in a prototype function of the super's child?

Now, I'm aware that the issue can be solved in another way, but I'm still curious if it's doable in the manner above.

Here's some reference code:

class Person {
        name;
        email;
        constructor(name, email){
            this.name = name;  
        }
    }
    Person.prototype.toString = function(){
      return `name: ${this.name}`
    }    


    class Teacher extends Person{
        constructor(name, subject){
            super(name);
            this.subject = subject;
        }
    }
    Teacher.prototype.toString = function(){
        return this.super.toString() + ` subject: ${this.subject}`
    }

    let teacher = new Teacher("testname", "testSubject");
    console.log(teacher.toString());

Upvotes: 3

Views: 1018

Answers (1)

Zevan
Zevan

Reputation: 10235

I don't believe super is available when you define a function on the prototype like that. Instead, you should define your methods within the class and use super.toString. Like this:

class Person {
  constructor(name, email) {
    this.name = name;
  }
  toString() {
    // you were missing `this` here
    return `name: ${this.name}`;
  }
}

class Teacher extends Person {
  constructor(name, subject) {
    super(name);
    this.subject = subject;
  }
  toString() {
    return super.toString() + ` subject: ${this.subject}`;
  }
}

let teacher = new Teacher("testname", "testSubject");
console.log(teacher.toString());

Upvotes: 2

Related Questions