JavaScript Inheritance Without Constructors

HTML5, CSS3 and JavaScript

The Fine Art of Web Development by Martin Ivanov

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

[sourcecode language=”javascript”]
(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());
})();
[/sourcecode]

Related Posts

Categories and Tags
Links

© 2006 - 2025 Martin Ivanov