Calling superclass constructors in JavaScript

I’ve recently been skimming Professional JavaScript for Web Developers by Nicholas Zakas… It’s a very interesting book that covers a lot of advanced JavaScript topics I haven’t seen in print (or anywhere) before.

Here’s one great trick that I’ve never seen or thought of before… simulating a call to a superclass’ constructor (think super() in Java) using the Function.call() built-in method that all classes (actually constructor functions) inherit. Here’s what it looks like:


function ParentClass() {
    this.name = 'dude';
}

function SubClass() {
    ParentClass.call(this);
}

var obj = new SubClass();
alert(obj.name);

Outputs:


dude

Some examples in the book combine this technique with the usual prototype chaining as described in David Flanagan’s excellent JavaScript: The Definitive Guide (related link) to simulate inheritance.

I’m glad I saw this, cuz I always considered calling a super class’ constructor to be impossible in JavaScript.

My tests show that this technique works in:

  • IE6
  • IE5.5
  • Gecko (Moz/FF/NN/Camino)
  • Safari (at least 1.2+ and probably all if I remember correctly)
  • OmniWeb 5+ (at least)
  • Opera (at least 7+)

Unfortunately, the Function.call() method does not work in:

  • IE 5 for Win
  • IE 5 for Mac

About this entry