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

14 comments

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>