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

planet1 = { name: "Jupiter", position: 8, type: "Gas Giant" }; showPlanet = function (planet) { var info = + ": planet " + planet.position; info += " - " + planet.type; ...

Get Get Programming with JavaScript 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.