July 13, 2012

Prototypal Inheritance

JavaScript has a different behavior from other modern programming languages, but it can simulate some aspects of them, for example classical inheritance. During the study and the use in practice of the language, I have not needed to use inheritance, I only knew that it exists, but I have not used it until I started to write some more complex and specific code. Then I needed a mechanism to reuse some parts of code that were repeated more than two or three times, which could be used in the future and could make the comprehension of the code more difficult.


I started to use the inheritance, I discovered various patterns to simulate the classical inheritance in JavaScript and chose one of them which corresponded to my needs and which I want to share:

    function Parent(/* some parameters */) {
        // Attributes and Methods
    }

    function Child(/* some parameters */) {
        // Calling Parent class constructor
        Parent.call(this /* some parameters */);


        // Child's Attributes and Methods
    }

    // Linking Child and Parent
    Child.prototype = new Parent();
    Child.prototype.constructor = Child;

Firstly, we have the parent class constructor, it can contain any attributes or methods, from this we will inherit its public members. Secondly, we have the child class constructor, inside it we need to call its Parent constructor and provide the current context, also, we can provide some additional parameters for the constructor. The child constructor can have its own members and can override the public members of its parent. Finally, we link the child and the parent by changing child's prototype, this will call parent's prototype every time when a new child instance will be created. We will need to change child's prototype constructor because all child instances will have parent constructor, which may confuse the user of these objects.

Another pattern which I liked is a little more tricky:

    function Child(/* some parameters */) {

        var thisInstance = new Parent(/* some parameters */);
        thisInstance.constructor = Child;


        // Adding new members to the parent instance
        // thisInstance.member = ...


        return thisInstance;
    }

This one creates a new instance of the parent constructor, then changes its constructor, adds some members and returns that instance. It is very similar to the previous one but in this case, we have to work with a parent instance instead of using current "this" instance.

No comments:

Post a Comment