How do I know if a variable is private?
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; }
};
})();
开发者_JS百科
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, _private
is "private" because, outside of the anonymous function, it is only accessible via the get
and set
functions your have provided. Without those functions, _private
would be totally inaccessible outside of the anonymous function.
Further reading:
- Private Members in JavaScript
- OOP in JS, Part 1 : Public/Private Variables and Methods
精彩评论