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?

Jamie Fearon
  • 2,574
  • 13
  • 47
  • 65

1 Answers1

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.

jmar777
  • 38,796
  • 11
  • 66
  • 64