Agile Zone is brought to you in partnership with:

I am a programmer and architect (the kind that writes code) with a focus on testing and open source; I maintain the PHPUnit_Selenium project. I believe programming is one of the hardest and most beautiful jobs in the world. Giorgio is a DZone MVB and is not an employee of DZone and has posted 636 posts at DZone. You can read more from them at their website. View Full User Profile

Classical inheritance in JavaScript

05.03.2011
| 6327 views |
  • submit to reddit

If you have written a bit of JavaScript, you certainly have heard the word prototype. Prototype is not only a JavaScript library, but also a key concept of JavaScript, which we will explore in depth today, without making your head spin.

(Almost) every object in JavaScript (where everything is an object, even functions) has an internal prototype property, which points in fact to a prototype object. When a method or property is missing on an object, it is searched on its prototype, and if not found on the prototype's prototype, and so on. the last object of the chain usually is Object.prototype.

Sometimes the prototype is exposed with the __proto__ property, although this is not part of the standard. According to the EcmaScript specification, it is a private property.

What you access with MyClass.prototype is instead a different thing. When you instance an object with new MyClass(), the object will its __proto__ set to MyClass.prototype; but MyClass.prototype is not in the prototype chain of MyClass. Its __proto__ instead is likely to be Function.prototype, since classes in JavaScript are defined as functions.

Only functions in JavaScript have this public property, which in fact can only be used for the valorization of the internal __proto__ of objects created by these functions.

A cool (but also dangerous) thing is that a reference is kept to MyClass.prototype, so you can add methods that work on *this* to MyClass.prototype later, and they will show up on every instance of MyClass, being shared by all of them.

Of course, since MyClass.prototype is an object just like everything else, its chain ultimately falls back to Object.prototype.

To implement classical inheritance, you have to leverage the prototype chains. Since properties and methods are searched on an object's __proto__, if you want it to inherit from another object you have to modify the prototype of its class (you can't modify __proto__).

Each instance of Dog now will inherit member fields from the new Animal() and consequently from Object.prototype.


This prototype chain can be technically extended as long as you want, each time by setting the prototype of the subclass equal to an object of the parent class. Of course from you should be wary of endless hierarchies.

This is the full code implementing these examples.

 

TestCase("playing with object prototypes in JavaScript", {
    "test object literals have natural prototype" : function () {
        var anObject = {};
        assertEquals(Object.prototype.toString, anObject.toString);
    },
    "test constructors have public prototype property" : function () {
        function MyClass() {};
        assertNotUndefined(MyClass.prototype);
    },
    "test objects do not have public prototype property" : function () {
        var anObject = {};
        assertUndefined(anObject.prototype);
    },
    "test objects created with a constructor has constructor property" : function () {
        function MyClass() {};
        var anObject = new MyClass();
        assertTrue(anObject instanceof MyClass);
        assertEquals(MyClass, anObject.constructor);
        assertEquals(MyClass.prototype, anObject.__proto__);
    },
    "test objects created with a constructor inherit from Object" : function () {
        function MyClass() {};
        var anObject = new MyClass();
        assertEquals(Object.prototype.toString, anObject.toString);
    },
    "test the prototype chain goes from instance to constructor" : function() {
        function MyClass() {};
        var anObject = new MyClass();
        MyClass.prototype.doSomething = function () {};
        assertEquals(MyClass.prototype.doSomething, anObject.doSomething);
    },
    "test the prototype chain goes also to Object" : function () {
        function MyClass() {};
        var anObject = new MyClass();
        Object.prototype.doSomethingElse = function () {};
        assertEquals(Object.prototype.doSomethingElse, anObject.doSomethingElse);
    },
    "test inheritance can be built by substituting prototypes with an object of the parent class" : function () {
        function Animal() {};
        Animal.prototype.eat = function() { return 'Yum'; };
        function Dog() {};
        Dog.prototype = new Animal();
        Dog.prototype.bark = function() { return 'Arf'; };
        Dog.prototype.constructor = Dog;
        var lassie = new Dog();
        assertTrue(lassie instanceof Dog);
        assertEquals('Arf', lassie.bark());
        assertTrue(lassie instanceof Animal);
        assertEquals('Yum', lassie.eat());
        assertEquals(Dog.prototype, lassie.__proto__);
        assertEquals(Animal.prototype, Dog.prototype.__proto__);
    },
    "test N levels of inheritance can be obtained by making each prototype an object which properties are inferred from parent prototype" : function () {
        function establishInheritance(childClass, parentClass) {
            childClass.prototype = new parentClass();
            childClass.prototype.constructor = childClass;
        };

        function Animal() {};
        Animal.prototype.eat = function() { return 'Yum'; };

        function Dog() {};
        establishInheritance(Dog, Animal);
        Dog.prototype.bark = function() { return 'Arf'; };

        function Collie() {};
        establishInheritance(Collie, Dog);

        var lassie = new Collie();

        assertTrue(lassie instanceof Collie);
        assertTrue(lassie instanceof Dog);
        assertTrue(lassie instanceof Animal);
        // inherits up to upmost class
        assertEquals('Yum', lassie.eat());

        assertEquals(Collie.prototype, lassie.__proto__);
        assertEquals(Dog.prototype, Collie.prototype.__proto__);
        assertEquals(Animal.prototype, Dog.prototype.__proto__);
    }
});
 
Published at DZone with permission of Giorgio Sironi, author and DZone MVB.

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)