Feed Sign in with OpenID OpenID

Simon Willison’s Weblog

A JavaScript Module Pattern. I’ve been using this pattern for a few months—it works really well, though I tend to keep my own code in my own namespace rather than adding it to YAHOO.

Tagged , ,

4 comments

  1. Do you find private methods and data useful? (Besides private-by-convention with a leading underscore)

    Personally I don't care any more in Javascript than I do in Python if someone wants to poke their way into my namespace. I guess in theory there could be some security concerns, but I can't actually think of an attack that would work that way.

    Ian Bicking - 13th June 2007 00:35 - #

  2. Yes, very. I don't use them to keep stuff private so much as I use them to manage my namespace. It's really handy to create a new module, define a bunch of private shortcuts and utility functions, then write a couple of big "public" functions and expose them explicitly to the rest of the world.

    If I end up wanting to reuse something I originally made private, I just add it to the list of functions to export at the end.

    Pretty much all of my modules start with "var $E = YAHOO.util.Event, $D = YAHOO.util.Dom;"

    Simon Willison - 13th June 2007 01:11 - #

  3. var that = this;

    if you need to avoid problems with the scope of your methods:

    Dinoboff - 13th June 2007 02:23 - #

  4. Private namespaces aren't a matter of security, but stability. If you box things off in your own namespace, there's less risk of inadvertently stomping on someone else's Javascript or having yours stomped on by something that gets loaded into the same page.

    If someone really wants to overwrite your functions, they can (and they may even have a good reason for doing so), and namespaces offer no protection. But that's not the goal anyway. They're more like the Perl encapsulation model as described in "Programming Perl": "Perl isn't obsessed with enforced privacy. A Perl module would prefer that you stay out of its living room because you weren't invited, not because it has a shotgun."

    Angus McIntyre - 13th June 2007 11:22 - #

Comments are closed.
A django site