0

I have a class called person:

function Person() {}

Person.prototype.walk = function(){
  alert ('I am walking!');
};
Person.prototype.sayHello = function(){
  alert ('hello');
};

The student class inherits from person:

function Student() {
  Person.call(this);
}

Student.prototype = Object.create(Person.prototype);

// override the sayHello method
Student.prototype.sayHello = function(){
  alert('hi, I am a student');
}

What I want is to be able to call the parent method sayHello from within it's childs sayHello method, like this:

Student.prototype.sayHello = function(){
      SUPER // call super 
      alert('hi, I am a student');
}

So that when I have an instance of student and I call the sayHello method on this instance it should now alert 'hello' and then 'hi, I am a student'.

What is a nice elegant and (modern) way to call super, without using a framework?

1

1 Answer 1

2

You can do:

Student.prototype.sayHello = function(){
    Person.prototype.sayHello.call(this);
    alert('hi, I am a student');
}

You could also make it a little more generic by doing something like this:

function Student() {
    this._super = Person;
    this._super.call(this);
}

...

Student.prototype.sayHello = function(){
    this._super.prototype.sayHello.call(this);
    alert('hi, I am a student');
}

...although, TBH, I don't think it's worth the abstraction there.

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

Comments

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.