I know you can achieve something as “privateness” in JavaScript by using closures and Immediate Invoked Functions.
But what if I need full featured prototyping? There simply is no way I know of of having private members in an object’s prototype. If I used privileged methods I can have private variables and public methods but I lose the option of prototyping.
Douglas Crockford “forbids” the use of dangling (putting an underscore in front of an identifier to indicate that it is not part of the public interface).
But is it that bad to use it? Since there is no way to make it real private.
What is your opinion about this? How do you handle it?
Well at first, you don’t really lose the prototyping-effect when using a functional-inheritance pattern. I just assume you’re talking about The good parts, crockford also introduced a pretty easy and effective way to have shared variables for that pattern aswell. Which basically looks like:
You can even simply extend this techniqe to have somekind of super methods. Using cryptic variable-conventions like underscores or whatnot is just bad practice in general. Its confusing since nobody just knows what is going on there (probably that argument fails if you’re the only one using the codebase).
However, ECMAscript Edition 5 introduces some goodys to have more “private” members in a prototype chain. One important method for that is
.defineProperty, where you can define a property which does not “shallow” through. Would look like:Now, the property
privateStuffis not visible for an object that inherits fromHuman‘s prototype chain. Anyway, this stuff requires Javascript 1.8.5 and is only available in cutting edge browsers for now. See https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object/defineProperty