Skip to content Skip to sidebar Skip to footer

Why Does Google's Closure Library Not Use Real Private Members?

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 C

Solution 1:

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.

Solution 2:

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.

Solution 3:

There's also more to the JSDOC notation than meets the eye--when you use the google closure compiler, those "@private" tags are parsed and enforced. If any external objects tries to access one of these variables, a compile error is generated. They do in fact have a philosophical objection to the general Crockford inheritance pattern: http://www.bolinfest.com/javascript/inheritance.php

Post a Comment for "Why Does Google's Closure Library Not Use Real Private Members?"