JavaScript Inheritance Without Constructors

Here’s a cool way for extending JavaScript objects without using constructors and “classes”, but simple literals/singletons, representing Base and Subclass objects:

(function() {
    "use strict";

    // the extend function
    function extend(superclass, subclass) {
        for(var key in superclass) {
            if(superclass.hasOwnProperty(key)) {
                subclass[key] = superclass[key];
            }
        }
    }

    // Base object
    var
        Base = {
            props: {
                firstName: "Martin",
                lastName: "Ivanov",
                web: {
                    site: "http://wemakesites.net",
                    blog: "http://acidmartin.wordpress.com/",
                    ui: "http://acidmartin.wordpress.com/",
                    twitter: "https://twitter.com/#!/wemakesitesnet"
                }
            },
            init: function() {
                window.console.log(">>> Base.init()");
            },
            getProperties: function() {
                return this.props;
            }
        };

    // directly call Base method if required
    Base.init();

    // inheriting object with some default methods
    var
        Subclass = {
            ownMethod: function() {
                window.console.log(">>> Subclass.ownMethod()");
            }
        };

    // extend the Subclass with properties from the Base object
    extend(Base, Subclass);

    // call some methods from the Subclass
    Subclass.init();
    Subclass.ownMethod();
    window.console.log(Subclass.getProperties());
})();

Related Posts

About these ads

14 comments

Leave a Reply

Please log in using one of these methods to post your comment:

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