Skip to Content
JavaScript Patterns
book

JavaScript Patterns

by Stoyan Stefanov
September 2010
Intermediate to advanced
236 pages
5h 47m
English
O'Reilly Media, Inc.
Content preview from JavaScript Patterns

Chapter 6. Code Reuse Patterns

Code reuse is an important and interesting topic simply because it’s natural to strive for writing as little and reusing as much as possible from existing code, which you or someone else has already written. Especially if it’s good, tested, maintainable, extensible, and documented code.

When talking about code reuse, the first thing that comes to mind is inheritance, and a great deal of the chapter is dedicated to this topic. You see several ways to do “classical” and nonclassical inheritance. But it’s important to keep the end goal in mind—we want to reuse code. Inheritance is one way (means) for us to reach that goal. And it’s not the only way. You see how you can compose objects from other objects, how to use object mix-ins, and how you can borrow and reuse only the functionality you need without technically inheriting anything permanently.

When approaching a code reuse task, keep in mind the advice the Gang of Four book has to offer on object creation: “Prefer object composition to class inheritance.”

Classical Versus Modern Inheritance Patterns

Often you hear the term “classical inheritance” in discussions on the topic of inheritance in JavaScript, so let’s first clarify what classical means. The term is not used in the sense of something antique, settled, or widely accepted as the proper way of doing things. The term is just a play on the word “class.”

Many programming languages have the notion of classes as blueprints for objects. In those languages ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Learning JavaScript Design Patterns

Learning JavaScript Design Patterns

Addy Osmani
Learning JavaScript

Learning JavaScript

Shelley Powers

Publisher Resources

ISBN: 9781449399115Errata Page