Chapter 5. Classes and Inheritance

None of the modules in the previous section were written in an object-oriented programming (OOP) style, but many of the modules in Closure are. Although JavaScript provides support for prototype-based programming (as opposed to class-based programming, which Java uses), the Closure Library approximates class-based programming using prototypes. In JavaScript: The Good Parts (O’Reilly), Douglas Crockford refers to this as the pseudoclassical pattern. This pseudoclassical pattern is chosen over the traditional cloning technique for creating objects used in prototype-based programming in order to conserve memory. Its style should be familiar to Java programmers. For these reasons, types are frequently referred to as classes in Closure, even though classes are not formally supported in JavaScript.

Many JavaScript developers balk at the idea of using OOP in JavaScript, arguing that its true beauty lies in its use as a weakly-typed language with first-class functions. Others say outright that OOP is fundamentally flawed, claiming that even Java guru Joshua Bloch thinks OOP is a bad idea, citing Item 14 of his preeminent book Effective Java (Addison-Wesley): “Favor composition over inheritance.” Those detractors fail to mention Bloch’s subsequent point, Item 15: “Design and document for inheritance or else prohibit it.” The two principal uses of inheritance in the Closure Library (goog.Disposable, explained in this chapter, and goog.events.EventTarget

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.