javascript interactive

JavaScript Interactive — a console crash course


5.6 Subclasses

Warning: Your browser may be outdated or unsupported.

The JavaScript console is known to display some of the examples incorrectly in Internet Explorer 8 or older.
  • When using static class-based objects, inheritance is a very important concept.
  • In a dynamic prototype-based language, it is more seldomly used.
  • And unfortunately it can also be a bit tricky to do correctly in JavaScript...
>>>
function MyObject() {};

  
>>>
MyObject.prototype.test = function () {
    return 123;
};

  
First, lets create a simple MyObject with a single method (in the prototype).
>>>
function SubObject() {};

  
>>>
SubObject.prototype = new MyObject();

  
The SubObject.prototype is replaced with an instance of MyObject in order to easily setup the prototype chain. But there are a few issues...
>>>
SubObject.prototype.constructor
function MyObject() {}
One problem is the constructor property. It is normally hidden inside the default prototype object, which has been replaced in this case.
>>>
SubObject.prototype.constructor = SubObject;

  
So the constructor should be restored to avoid confusion.
>>>
new SubObject()

  
The SubObject instances will now inherit the methods from the parent object.
>>>
print(new SubObject(), true);

  
A debug printout clearly shows the prototype chain. But now some other problems might stand out. What if the MyObject constructor used arguments? Or initialized instance properties?
>>>
function NextObject() {
    MyObject.call(this);
}

  
Things immediately get more complicated. First, the parent object constructor have to be called from the sub-object.
>>>
NextObject.prototype = Object.create(MyObject.prototype);

  
>>>
NextObject.prototype.constructor = NextObject;

  
Secondly, the prototype chain should be setup without calling the constructor function. This avoids setting any instance properties to the prototype objects.
>>>

Index 1 2 3 4 5 6 7 8