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.name + ": planet " + planet.position;
    info += " - " + planet.type;
    console.log(info);
};

showPlanet(planet1);

into

planet1 = buildPlanet("Jupiter", 8, "Gas Giant");
planet1.show();

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.

9.1. Using functions to build objects

9.2. Using constructor functions to build objects

9.3. Building mastery—two examples of constructors

9.4. The Crypt—providing places to plunder

9.5. The Crypt—streamlining player creation

9.6. Summary

sitemap