I've been a JavaScript developer for a while now, and I've always thought that the correct way to implement private members in JavaScript is to use the technique outlined by Doug Crockford here: http://javascript.crockford.com/private.html.
I didn't think this was a particularly controversial piece of JavaScript wisdom, until I started using the Google Closure library. Imagine my surprise... the library makes no effort to use Crockford-style information hiding. All they do is use a special naming convention and note "private" members in the documentation. I'm in the habit of assuming that the guys at Google are usually on the leading edge of software quality, so what gives? Is there some downside to following Mr. Crockford's advice that's not obvious?
The Closure Library serves as the base JavaScript library for many Google products, including: Now that the Closure Library is open source, more and more developers outside Google are integrating the library in their own projects.
If you are developing a large or growing application, you may benefit from the Closure Library's breadth. A well-tested library can insulate you from cross-browser compatibility issues and the minutiae of client-side programming, letting you focus on the fun stuff.
Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0 License, and code samples are licensed under the Apache 2.0 License. For details, see the Google Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.
There are a lot of examples of pseudo-privacy in main-stream JavaScript libraries. Facebook Connect's JavaScript library has the same structure.
The main reason developers go that route is for performance. Hiding things in closures can be slower and use more memory. Closure-hiding can also be less flexible, as true privacy can't be carried between files without some clever hacks. Closure-hiding is more conceptually pure, IMO, but when performance is a concern, using pseudo-privacy is the way to go.
The other reason is that a lot of Google programmers have backgrounds in Python, where there are no private anythings and the underscore prefix is the accepted community standard.
Their inheritance model using goog.inherit() and goog.base() simply copy prototype members from the superclass to the subclass.
You can see that the sugar function from Doug Crockford does the same. I have personally faced lots of problems while inheriting a privileged member (this.property).
With both methods of inheritance, the private variables simply disappear as unlike C++ or Java where you have no access to the superclass' private members but they are still inherited. This has to be the major reason they prefer this approach.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With