Implementing the super keyword in JavaScript

Published on 9th of February 2009. Copyright Tavs Dokkedahl. Displayed 6788 time(s)

JavaScript has no notion of the super keyword but it can be implemented in a variety of ways.

I friend of mine was struggeling with understanding inheritance in JavaScript. Coming from the world of Java he was used to having the super keyword and would like JavaScript to support this as well.

Super is used to reference a method of an objects parent class when the object itself is overridding the parent method. It is best explained by an example.

 1 // Java example of super
 2 //
 3 // Define parent class
 4 public class Parent {
 5   public void myMethod() {
 6     System.out.println(\"myMethod called in Parent Class\");
 7   }
 8 }
 9 // Define child class which extends
10 // the Parent class
11 public class Child extends Parent {
12   // Override myMethod of Parent class
13   public void myMethod() {
14     super.myMethod();
15     System.out.println(\"myMethod called in Child Class\");
16   }
17 }

If we create an instance of the Child class and call the myMethod we get

 1 // Create new instance of Child class
 2 c = new Child();
 3 // Call myMethod on instance
 4 c.myMethod();
 5 // Output is:
 6 // 'myMethod called in Parent Class'
 7 // 'myMethod called in Child Class'

So the super keyword calls the method of the parent class.

To create similiar functionality in JavaScript we write an extend method to use on constructors

 1 // Create extend method
 2 Function.prototype.extend =
 3   function(pObj) {
 4     // Inherite from pObj
 5     this.prototype = new pObj();
 6     // Create ref. to parent object
 7     this._super = pObj.prototype;
 8     // Reset constructor ref.
 9     this.prototype.constructor = this;
10   };

As super is a reserved keyword in JavaScript we use _super instead. A translation of the Java example to JavaScript could be

 1 // JavaScript example of super
 2 //
 3 // Define parent class
 4 function Parent {
 5 }
 6 Parent.prototype.myMethod =
 7   function() {
 8     alert('myMethod called in Parent Class');
 9   };
10 // Define child class
11 function Child() {
12 }
13 Child.prototype.myMethod =
14   function() {
15     this._super.myMethod();
16     alert('myMethod called in Child Class');
17   };
18 // Child extends Parent
19 Child.extend(Parent);

So what is super in Java is the equivalent of this._super in JavaScript in some sense

 1 // Create new instance of Child class
 2 var c = new Child();
 3 // Call myMethod on instance
 4 c.myMethod();
 5 // Output is:
 6 // 'myMethod called in Parent Class'
 7 // 'myMethod called in Child Class'

The functionality is not identical but it comes pretty close.


Leave a comment

Name

Email (if you want a response)

Comment (no HTML)

Spam challenge
Sorry to bother you but spam is a royal pain, so please answer this simple question to verify that you are in fact human(oid)

Question: "What is the opposite of upload?"

Answer: