I’ve never understood private variables. I know how to make them, (using the Module Pattern, right) but I don’t see what’s so private about them. I illustrated an explanation on jsFiddle — http://jsfiddle.net/fufWX/
Can you explain how that _private variable really is private when it is still accessible from the outerscope? And what are the use for private variables in the first place!? Thanks.
var Module = (function() {
var _private = "My private variable";
return {
get: function() { return _private; },
set: function(e) { _private = e; }
};
})();
var obj = {};
// How is that variable private when I can simply obtain it like this:
obj.get = Module.get; // ??
obj.set = Module.set; // ??
obj.get(); // "My private variable"
There’s no such thing as a truly private variable in JavaScript. There are only local variables.
In your example,
_privateis “private” because, outside of the anonymous function, it is only accessible via thegetandsetfunctions your have provided. Without those functions,_privatewould be totally inaccessible outside of the anonymous function.Further reading: