How to emulate private vars in Javascript

As you know, the object members of an object are all public in Javascript.
There is no mechanism to declare a protected or private variable.

In some situations, using private variables would be needed though, like if for instance you are building a library that is meant to be used by other people.
In his excellent short book Javascript, the Good parts, Douglas Crockford, the father of JSON, explains how to do it:

var o = function(){
    var _my_private_var = "I am private";
    return {
        test: function(){
            alert("I am a plublic method, having access to a private var: " + _my_private_var);
o.test(); // will display the message

The trick here is to use a function to define the object o.

In Javascript, all functions are closures, meaning that they embed a reference to the context where they were created.
The second point to know is that, contrary to C, where the scope is defined per block, the scope in javascript is defined per function. If you define a child function inside a parent function, the child will have access to the variables that were declared in the parent.

Finally, in order to be sure not to be able to get a way to access directly our private variable, we use an anonymous function, that we immediately call (note the “}();” at the end) to return the object.

So, what is happening here is that when we call the “test” method, it has still access to the context where it was defined (closure property). In this case, the context is our anonymous function.
As _my_private_var is defined inthere, it is visible from test().

On the other hand, we did not store a reference to the anonymous function. o only contains a reference to the returned object. So there is no way to access _my_private_var from the outside anymore.
Note that as functions are also objects in Javascript, we could access _my_private_var if we had kept a reference to the object generation function.

var func = function(){
    var _my_private_var = "I am not that private";
alert(func._my_private_var); // Will display "Im am not that private"
  1. No comments yet.

  1. No trackbacks yet.