Object-oriented JavaScript
class members

The page on inheritance showed how to use closures to implement proper inheritance of object members. The problem there was that using the constructor prototype directly resulted in all the public members of a prototype parent object being shared by the child objects. Here, the aim is the other way around: to define shared member variables of child objects, which are not members of the parent objects.

The trick is this: the shared members belong to the child constructor.

In the literature of class-based object-oriented languages, such shared members are called class members because there is only one copy of each member per class. (Here we could call them “constructor members”. But this is an artificial distinction: it would only serve to emphasize the programming technique used.)

A closure can be used also to define class members.

example

Start from the same typical parent class as in the page on inheritance



Now define a child constructor, which has private members to be shared by all the child objects, and public methods that can access the shared private members.



Note the commas between the declarations of the private members in the assignment of ChildByClosure.prototype. These are comma operators, which evaluate each expression in turn, and result in the value of the final expression. Here the value of the final expression is the single unnamed function.

The following set of parentheses evaluates the function. This creates a new Parent object. But the private class members are in the scope containing the function, and so form a closure with it.



Now cc1 and cc2 have separate copies of their parent’s member prop2.

So the property prop3 is visible within the child code, and both child objects share the same copy of it. But this property is not visible from outside the ChildByClosure code.

See

Javascript Closures

Richard Cornford, Private Static Members in Javascript (previously in a JS Intro page which is unavailable as of this writing)

JavaScript Closures