Feed Sign in with OpenID OpenID

Simon Willison’s Weblog

Why I don't love JavaScript's Module Pattern. Jonathan Snook points out that the module pattern (where private functionality is hidden in a closure and only public methods are revealed to outside scopes) makes code a lot harder to debug. I use the module pattern for pretty much everything, not because I want to keep stuff private but more to avoid any chance of leaking out in to the global namespace. If I need to debug a value I temporarily assign it as a property on the global window object.

Tagged , , , ,

2 comments

  1. Yeah, I'm a big fan of it too. Private properties and such, sure, but most of all, I find it much easier to do some nice code within the closure at hand then... :-)

    Robert Nyman - 1st May 2009 02:31 - #

  2. You can also add this method to the object your Module returns:

    
    'get': function(prop) {
        //FIXME: Don't leave this in production code!
        try { 
            return this[prop]();  
        }
        catch (e)  { return eval(prop); }
    }
    
    

    As the comment indicates, you do not want to leave this in production code, but it's great for accessing private props and functions.

    I started using the module pattern when I switched to jQuery from Prototype and lost function methods like bind() and bindAsEventListener().

    James Sevenson - 1st May 2009 03:00 - #

Sign in with OpenID

Auto-HTML: Line breaks are preserved; URLs will be converted in to links.

Manual XHTML: Enter your own, valid XHTML. Allowed tags are a, p, blockquote, ul, ol, li, dl, dt, dd, em, strong, dfn, code, q, samp, kbd, var, cite, abbr, acronym, sub, sup, br, pre

A django site