After having read Douglas Crockford’s book “Javascript: The Good Parts”, I had learned some ways to leverage objects and information hiding in Javascript. For example:
var fooInstance = function() {
var privateAlpha;
return {
getAlpha: function() {
return privateAlpha;
},
setAlpha: function(a) {
privateAlpha = a;
}
};
}();
fooInstance.setAlpha(10);
console.log(fooInstance.getAlpha()); //10
fooInstance.setAlpha(20);
console.log(fooInstance.getAlpha()); //20
However, if you do a quick search on StackOverflow, you’ll quickly encounter a huge number of answers on javascript questions which say not to bother with private variables. Their reasoning is “well, you can just look at the javascript source in the browser, so what’s the point?”. This is missing part of the point.
One of the primary points of encapsulation is to control the internal state of the object, by only providing a limited interface. This protects the integrity of the state.
But the other purpose of private variables and encapsulation in any language is not simply security or protection from nefarious people. It’s abstraction. An external entity should not need or care to know how the internals are accomplished. The smaller the footprint of the interface, the less complexity exists for the consumer to understand. You should expose no more than is necessary to leverage the functionality. The result of doing so is code that has looser coupling and is easier to understand by those who wish to consume it.