JavaScript. Private members (instance variables).
March 13, 2008
As you know JavaScript has no concept of private members in objects. Objects there are “racks of properties” that anyone can change.
Here is a simple way of making “objects” in JS that have private instance variables. Such variables can be changed only by [public] methods you provide.
Consider following code:
function CreateMyObject()
{
var m_first = 0;
var m_second = 0;
var envelope = // our public interface
{
getFirst: function() { return m_first; },
setFirst: function(v) { m_first = v; },
getSecond: function() { return m_second; },
setSecond: function(v) { m_second = v; }
};
return envelope;
}
var f = CreateMyObject();
var n = f.getFirst(); // calling our methods
Here we have CreateMyObject() that behaves as a constructor of our object. It returns envelope object that has four methods. Only these methods can update or retrieve state of m_first and m_second variables. There are literally no other ways to access them from anywhere else other than set of methods provided.
Under the hood: In this example each interface method that we’ve created is a closure in fact: such methods have access to environment of outer function (CreateMyObject in this case) so they can access variables in this environment. Making a closure can be a memory expensive operation so avoid their use when you expect many instances of such objects.

