Inheritance and super

It is worth pointing out that, strictly speaking, JavaScript (pre version 2) has no such thing as classes. It has functions, and if you put the word new in front of a function call it creates a new object using that function. It uses prototypal inheritance, in which objects inherit from other objects rather than classes from classes. JS.Class attempts to gloss over all that and to make JavaScript more like a classical language.

To create a subclass of, say, Animal, you pass it in as the first argument when creating a new class. Recall our Animal class:

        var Animal = new JS.Class({
          initialize: function(name) {
            this.name = name;
          },
          speak: function(things) {
            return 'My name is ' + this.name + ' and I like ' + things;
          }
        });

We can create a class Dog as follows:

        var Dog = new JS.Class(Animal, {
          speak: function(stuff) {
            return this.callSuper().toUpperCase() + '!';
          },
          huntForBones: function(garden) {
            // ...
          }
        });

Dog does not need its own initialize() method as it inherits one from Animal. However, it chooses to override the speak() method with its own version.

Now we come to a special method generated by JS.Class, called callSuper(). This method gets created dynamically inside method calls and allows you to access the current method in the parent class. Like in Ruby, you don’t have to pass any arguments to callSuper(), thus avoiding repetition.

        var rex = new Dog('Rex');
        rex.speak('barking')
            // -> "MY NAME IS REX AND I LIKE BARKING!"

callSuper() is not accessible from outside the object:

        rex.callSuper();
            // -> rex.callSuper is not a function

You can pass arguments to callSuper() to override the ones passed in automatically, e.g.:

        var Dog = new JS.Class(Animal, {
          speak: function(stuff) {
            stuff = stuff.replace(/[aeiou]/ig, '_');
            return this.callSuper(stuff).toUpperCase() + '!';
          }
        });
        
        var rex = new Dog('rex');
        rex.speak('something')
            // -> "MY NAME IS REX AND I LIKE S_M_TH_NG!"