Reputation: 44295
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:
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?
Upvotes: 2
Views: 139
Reputation: 69964
The whole purpose of encapsulation and private variables, in Javascript or any other language, is to restrict yourself in a way that allows the implementation of a class to be changed at any time without breaking the rest of the code. You can rename secret to any other name or completely remove it and be sure that the code would continue to correctly work.
On the other hand, a public method is a point of coupling between the producer and the consumer and you can't easily change the public interface, method names or arguments without risking to break other parts of the program that depend on it. (This is completely unrelated to wether the code has been obfuscated or how weel docomented it is - if someone is using a public method the coupling will already be there)
Upvotes: 3
Reputation: 37516
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.
Upvotes: 2
Reputation: 349232
Local ("private") variables are very useful to keep the code readable. Not only because of descriptive names, but also because a developer don't have to keep track of 1000+ variable names.
Also, some variables shouldn't be able to be changed "from the outside". Consider:
function (){
var password = "random word";
window.passwordAsker = function(){
var asked = prompt("Password?", "");
if(asked == password) {
alert("Access granted"); //This should NOT be a real verification method
}
}
}
Upvotes: 1