Javascript Pseudo-global “Private” variables

Once upon a time, it was thought that Javascript didn’t have private or protected member class variables and methods. Crockford showed us that this was false.

Globals are generally frowned upon, with very good reason. They open the door for conflicts and unpredictable behavior when you’re using scripts from different places. There are enough technical issues to worry about in building a web page, and often the biggest of these is human error. Programming discipline is the way to minimize human error. Scope is good programming discipline.

However, in this new world order of no-globals, it made me wish for a simpler time, when you just declared everything inside the SCRIPT tag, secure in the knowledge that it would never be overwritten. Globals are a very convenient way to provide communication between multiple instances of a class. Without globals, we’re forced to hang data on the DOM, which is great for lightweight pages, but can get very slow as the number of HTML elements increases.

Thankfully, the lispy Javascript paradigm allows you to have “pseudo-global” variables, accessible to your objects, but completely hidden from the rest of the world. Not only can you create private shared variables, but you can also provide restricted read/write access to them via privileged member methods. This gives Javascript the ability to have “get” and “set” properties, which is the only thing I truly missed from VB.

It’s my new flavor-of-the-week. Not only is it good for cross-instance communication, it’s also useful for establishing shorthand for your long-named objects. Since I tend to write YAHOO.util.Dom and YAHOO.util.Event over and over again, I simply assigned them to the pseudoglobal vars $D and $E.

I’m sure I’m not the first Javascripter to come up with this concept, but I haven’t seen it around much, so I’m sharing it. Enjoy :)

[The requested file /home/yaohytmw/ could not be found]

Leave a Reply

Comments are moderated like crazy using a variety of plugins. There is a very high likelihood that your comment won't show up right away, especially if you have never commented here before, but it was not deleted.

Please be patient, and do not post your comment more than once. It will show up once it is approved.

You must be logged in to post a comment.