2

Provided the following code:

class Person {
    constructor(name) {
        this.name = name;
    }
    sayHello() {
        console.log('Hello, my name is ' + this.name);
    }
    sayHelloAndBy() {
        this.sayHello();
        console.log('Bye');
    }

}
class Student extends Person {
    constructor(name, grade) {
        super(name);
        this.grade = grade;
    }
    sayHello() {
        console.log(`Hi, I'm a studend and my name is ` + this.name);
    }
}


let b = new Student("Some guy", 5);

b.sayHelloAndBy();

I would like to figure out a way of calling sayHello as defined in Person and not in Student. Is it possible ?

In php there is the self:: which allows one to do this, but I'm not sure if JS has a similar concept.

6
  • Depends from where you want to call it. So, where do you want to call Person’s sayHello method ? Commented Oct 17, 2017 at 14:25
  • You can use super in methods to refer to an overridden parent method. Commented Oct 17, 2017 at 14:25
  • 1
    Person.prototype.sayHello.call(this) Commented Oct 17, 2017 at 14:25
  • super. sayHello would be the one that you are looking for Commented Oct 17, 2017 at 14:25
  • @Ryan That would change the context inside sayHello. this would point the child not the parent inside of sayHello. Commented Oct 17, 2017 at 14:27

1 Answer 1

4

You can refer to the version of sayHello defined in Person through Person’s prototype property and call it with the requisite this using Function#call:

sayHelloAndBye() {
    Person.prototype.sayHello.call(this);
    console.log('Bye');
}

Runnable:

class Person {
    constructor(name) {
        this.name = name;
    }
    
    sayHello() {
        console.log('Hello, my name is ' + this.name);
    }
    
    sayHelloAndBye() {
        Person.prototype.sayHello.call(this);
        console.log('Bye');
    }
}

class Student extends Person {
    constructor(name, grade) {
        super(name);
        this.grade = grade;
    }
    sayHello() {
        console.log(`Hi, I'm a studend and my name is ` + this.name);
    }
}

let b = new Student("Some guy", 5);

b.sayHelloAndBye();

Sign up to request clarification or add additional context in comments.

2 Comments

I'm pretty sure this is what the OP is looking for.
However, if that’s the desired behavior a cleaner approach might be to put the logic into a new method that’s not supposed to be overwritten. I.e. _sayHello() {...} sayHello() { this._sayHello();} sayHelloAndBy() { this._sayHello();...} (or simply define a function outside the class and call that one).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.