CHAPTER 10 Ensuring Correct Implementation of the Factory Pattern

WHAT’S IN THIS CHAPTER?            

  • Unit-testing a factory
  • Writing a reliable factory

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. The files are in the Chapter 10 download and are individually named according to the filenames noted throughout this chapter.

In JavaScript, a factory is simply a function whose purpose is to build and return an object. Factories abound in JavaScript. The Object.create method introduced in ECMAScript 5 is a factory built into the language. You have also met many factories in this book, although under other names. For example, a module technically meets the definition in that its purpose is to create and return an object, albeit with some data-hiding in the bargain.

Why would you want to use a factory to create an object instead of new or an ordinary function call? Broadly speaking, there are two reasons: increased control and increased abstraction. In this chapter, you will work with an example that illustrates both.

WRITING UNIT TESTS FOR A FACTORY

The JavaScript conference whose website you are developing will be packed with presentations. Your next job is to model these presentations for the site.

There are two kinds of presentations: regular presentations and presentations by vendors. The basic presentation has a title and an optional presenter. (Sometimes a presentation ...

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.