javascriptobject-literal

JavaScript - Advantages of object literals


I've read that rather than simply writing a bunch of functions, I should use an object literal.

What are the advantages of object literal, with examples?


Solution

  • As Russ Cam said, you avoid polluting the global namespace, which is very important in these days of combining scripts from multiple locations (TinyMCE, etc.).

    As Alex Sexton said, it makes for good code organisation as well.

    If you're using this technique, I'd suggest using the module pattern. This still uses object literals, but as the return value from a scoping function:

    var MyThingy = (function() {
    
        function doSomethingCool() {
            ...
        }
    
        function internalSomething() {
            ....
        }
    
        function anotherNiftyThing() {
            // Note that within the scoping function, functions can
            // call each other direct.
            doSomethingCool();
            internalSomething();
        }
    
        return {
            doSomethingCool: doSomethingCool,
            anotherNiftyThing: anotherNiftyThing
        };
    })();
    

    External use:

    MyThingy.doSomethingCool();
    

    The scoping function is wrapped around all of your functions, and then you call it immediately and store its return value. Advantages:

    Example of returning different functions:

    var MyUtils = (function() {
        function hookViaAttach(element, eventName, handler) {
            element.attachEvent('on' + eventName, handler);
        }
    
        function hookViaListener(element, eventName, handler) {
            element.addEventListener(eventName, handler, false);
        }
    
        return {
            hook: window.attachEvent ? hookViaAttach : hookViaListener
        };
    })();
    
    MyUtils.hook(document.getElementById('foo'), 'click', /* handler goes here */);