CHAPTER 3 Constructing Reliable Objects

WHAT’S IN THIS CHAPTER?            

  • Creating data as primitives, object literals, and modules
  • Creating data with the new keyword
  • Using methods of object creation to produce reliable objects
  • Controlling inheritance using prototypal, classical, and functional patterns
  • Using monkey-patching responsibly

WROX.COM CODE DOWNLOADS FOR THIS CHAPTER

The wrox.com code downloads for this chapter are found at www.wrox.com/go/reliablejavascript on the Download Code tab.

Developers love dazzling effects in the user interface, elegant algorithms, and well-designed APIs, but often give little regard to the humble act of instantiating an object. JavaScript offers an unusually varied assortment of choices for doing just that. Some of them will make your code reliable, testable, and extensible; others represent the easy road to perdition.

This chapter surveys the most common ways to create an object, considering how well each one meets the SOLID and DRY criteria for reliability and testability introduced in Chapter 1.

Let’s start with the most basic and build our way up.

USING PRIMITIVES

When we are hiring developers, we always ask candidates, “What are the primitive data types in JavaScript?” The most common answer is, “Just one: var.” The next-most-common response is the opposite: to take a deep breath and rattle off enough types to fill a C# manual. Neither answer is correct.

JavaScript has exactly five primitive data types: String, Number, Boolean ...

Get Reliable JavaScript: How to Code Safely in the World's Most Dangerous Language 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.