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 ...
Get Closure: The Definitive Guide now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.