About Me

My photo
Experienced Web Developer using C#, ASP Classic (VBScript) and ASP.NET, MySQL, T-SQL, and other SQL variants, JavaScript (W3Schools Certified and very well versed in jQuery and learning Dojo), and XML. Heavy interest in JavaScript, framework creation on various language platforms, and keeping up with the best industry-accepted practices.

Tuesday, July 10, 2012

Truly Private Variables in JavaScript

So, I'm creating a module system for a project I'm working on, and I wanted to share a design pattern that I am using, that allows for private variables to be attached to an object. So private, in fact, that they don't even show up when you console.log the saved variable.

To see how this works, let's dive into the code for the basic module.



Simple enough. Now let's take a look at the modules class, and its register function. As a side note, Sandbox is a class that is passed to every module, which allows it to perform various functions, e.g. pub/sub.



So, now let's create an initialize a module.

As you can see, the sandbox, instance, factory, and initialized properties that were added to the module object in the "register" function are hidden from the console.log view. I can then, inside the modules class, call the modules[module.uuid].factory or sandbox or whatever, and it will be available from within the class. If you want to have access to these properties, you would simply return the module object in place of the prototype, or perhaps in place of the instance. You could also add a getter to the class to return a module by its uuid, and you would have access to those private variables.

For more information on closures (the reason this works), you can visit a really concise explanation by Douglas Crockford here.