Private Variables and Other JavaScript Links

JavaScript LinksA few handy links about JavaScript techniques.

I find the last one on JavaScript’s module pattern most interesting. It’s main reason for existing is to add the concept of private variables to a language which was designed without any access controls. It reminds me a lot of the argument around typing in languages. Many people think having the compiler enforce variable types leads to fewer bugs, in this case the compiler is enforcing access controls.

If you’re using a language that’s designed to be very dynamic and not have restrictions, it feels wrong to try and add them in using approaches like the module pattern. Even though I’d cringe if I saw a variable marked public in Java without also being final and static (i.e. a constant), I find making variables private using a convention like prefixing the name with underscore the most natural approach in JavaScript.

One Response to “Private Variables and Other JavaScript Links”

  1. ddoctor Says:

    Yeah, I’d have to agree.

    I’m all for design patterns when they solve a common problem in an elegant way. But that ‘Module’ pattern seems to be an attempt to give the language a feature it doesn’t have natively and the syntax of it feels very clumsy. I think some people have a innate beliefs about “How Programming Must Be Done” and try and push languages and technologies until they work The Right Way.

    You really need to work with the grain of a language, not fight it.

    Part of the justification behind private members and the get/set pattern is access control for the sake of preventing accidental mutation. A lot of these risks can be mitigated with testing… or with a naming convention, like you suggested.

    The equivalent in pseudoclassical is something like this (not that I advocate psuedoclassical, but for interest’s sake):
    var blah = new function() {
    var myCollection = [];
    this.add = function(item) {
    myCollection.push(item);
    }
    };

    The concept is the same – using closure over a function-scoped variable.

    In the article see “Make extending easier”… well, we’re not actually creating a private variable – it’s a variable accessed via closure. Looks similar, but it’s not, so you shouldn’t expect it to be. The key difference is: private variables are in scope in all methods of the object, whereas javascript variables have function (or global) scope which is available via closure in functions defined in the same context. It matters where the function is defined, not what object it is attached to.


Leave a Reply

(Valid OpenIDs will skip moderation)

Alternatively, subscribe to the Atom feed.