Vishful thinking…

Writing better javascript – Part 10

Posted in javascript by viswaug on November 29, 2008

Parasitic Inheritance

I had written about using the JavaScript module pattern to better organize and structure your code. If you like using the module pattern and are liking it enough to be writing complex code libraries with it, then you might want to explore and utilize OO inheritance in your classes. This can be achieved by using the parasitic inheritance pattern.

Let’s say that you have written a base class called ‘MapToolbarItem’ using the module pattern like below.

Base Class

var MapToolbarItem = function(toolbarItemID, options) {
    //Declare private variables here
    var _element;

//Declare private methods here
    var _enable = function() {
        //implement function here
    };

var _disable = function() {
        //implement function here
    };

return {
        //Declare public variables here
        element: _element,

//Declare public methods here
        enable: function() {
            _enable();
        },

disable: function() {
            _disable();
        }
    };
};

The class below illustrates how to create a ‘MapTool’ class that inherits from the ‘MapToolbarItem’ class using the parasitic inheritance pattern.

Inherited Class

var MapTool = function(toolID, options) {

//Declare a variable (called ‘that’ here) and assign an instance of the base class to it
    var that = new MapToolbarItem(toolID, options);

//Declare private variables here
    var _state;

//Declare private methods here
    var _select = function() {
        //Implement function here
        //Public variables of the base class can be used here
        that.enable();
    };

var _unselect = function() {
        //Implement function here
        //Public variables of the base class can be used here
        var el = that.element;
    };

//Declare public variables here
    //The public variables are created on the ‘that’ variable holding the base class instance
    that.state = _state;

//Declare public variables here
    //The public methods are created on the ‘that’ variable holding the base class instance
    that.select = function() {
    };

that.unselect = function() {
    };

//return the ‘that’ object
    return that;
};

The pattern is pretty simple enough where new public variables and methods are attached to an instance of the base class and then the instance of the base class is returned

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: