O'Reilly logo

Closure: The Definitive Guide by Michael Bolin

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Appendix A. Inheritance Patterns in JavaScript

This originally appeared as an article on my website on November 6, 2009.

The Closure Library makes use of the pseudoclassical inheritance pattern, which is particularly compelling when used with the Closure Compiler. Those of you who have read JavaScript: The Good Parts by Douglas Crockford (O’Reilly) may use the functional pattern for inheritance that he espouses.

Crockford appears to object to the pseudoclassical pattern because “There is no privacy; all properties are public. There is no access to super methods . . . . Even worse, there is a serious hazard with the use of constructor functions. If you forget to use the new prefix when calling a constructor function, then this will not be bound to a new object . . . . There is no compile warning, and there is no runtime warning” (p. 49).

This appendix discusses the advantages of the pseudoclassical pattern over the functional pattern. I argue that the pattern used by the Closure Library paired with the Closure Compiler removes existing hazards, and I also examine the hazards introduced by the functional pattern (as defined in JavaScript: The Good Parts). First let me demonstrate what I mean by the functional pattern.

Example of the Functional Pattern

The following example demonstrates the style of the functional pattern for inheritance as explained in Douglas Crockford’s JavaScript: The Good Parts. It contains the definition for a phone type as well as a subtype smartPhone.

var phone ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required