Chapter 3. Objects: grouping your data

 

This chapter covers

  • Organizing information with JavaScript objects
  • Creating objects
  • Adding properties to objects
  • Accessing properties using dot notation
  • Examples of objects

In chapter 2 you saw how to declare variables and assign them values, and you considered the variables you could use to model a player in The Crypt. As your programs grow, so does the number of variables you use; you need ways to organize all this data, to make your programs easier to understand and easier to update and add to in the future.

Sometimes it makes sense to group items and see them as a whole. Consider a first-aid kit; we happily treat it as a single item—“Have you packed the first-aid kit?” “Pass the first-aid kit.” “We need the first-aid kit, now!”—but will quickly switch focus to its contents when the need arises—“Pass the antiseptic and the bandages from the first-aid kit, please.” A number of items is neatly encapsulated by a single object.

This chapter introduces JavaScript objects, a simple and efficient way to collect variables together so that you can pass them around as a group rather than individually.

3.1. A need for organization

Your library of adventure stories is growing, and you decide to write a program to keep track of your precious collection. The following listing shows variables you use to generate this test output on the console:

> The Hobbit by J. R. R. Tolkien

3.2. Creating objects

3.3. Accessing object properties

3.4. Updating object properties

3.5. Further examples

3.6. The Crypt—a player object

3.7. Summary

sitemap