Private Variables and Other JavaScript Links
Adrian Sutton
A few handy links about JavaScript techniques.
- Loading Scripts Without Blocking – Steve Souders
- Coupling Asynchronous Scripts – Steve Souders
- Why I Don’t Love JavaScript’s Module Pattern – Jonathan Snook
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.