Chapter 9. Constructors: building objects with functions
This chapter covers
- Using functions to create objects
- The keyword new
- Using constructor functions to create objects
- The special variable this
- Defining constructor functions for players and places
It’s common for programs to create many similar objects—a blog post could have hundreds of posts and a calendar thousands of events—and to include functions for working on those objects. Rather than building each object by hand using curly braces, you can use functions to streamline the process. You want to change
where the buildPlanet function creates the planet object for you and adds the show method automatically. You define a blueprint for your object in the function body of buildPlanet and then use that blueprint to generate new objects whenever you need them. That keeps your object-creation code in one place; you’ve seen throughout the book how such organization makes it easier to understand, maintain, and use your programs.