First, my experience with JavaScript is limited to web development and a little self-study. I want to understand the point of having private members in JavaScript. Take an example,
var myObject = {
WriteWord: function() {
var secret = 'word';
document.writeln(secret);
}
};
myObject.WriteWord();
Private variable secret cannot be seen by the caller. AFAIK, I can notify potential callers of the existence of WriteWord in a few ways:
- Document the code. Like jQuery does.
- For .NET guys, write a custom visual studio intellisense plugin.
- Read the code directly.
Now let’s say I minify and even obfuscate the code. Its now unreadable. In my mind, given this scenerio, a lack of documentation is just as good as a private variable.
Is this scenerio uncommon or somehow wrong? What is the importance of private variables in JavaScript?
Scoping variables carefully in JavaScript eliminates the possibility of another script on your page clobbering a variable.
This becomes a valid concern when working with many different JavaScript libraries/files from possibly many different programmers.