Contents


Practice: Creating objects with JavaScript

Comments

These exercises give you practice in:

  • Creating objects using the Object function
  • Creating objects using literal notation
  • Creating objects using the object constructor and prototypes
  • Adding properties to each object type
  • Adding methods to each object type

To work through the exercises in this article, you should have an HTML editor and a working Internet connection or localhost environment in which to test your JavaScript.

Exercise 1: Create objects using the Object function

The Object function provides a simple way to create a new instance of an object. After an object is created, it's just as easy to define new properties and methods. To do so, perform these tasks:

  1. Create an object using the Object function.
  2. Add a property to the new object.
  3. Add a method to the new object.

Exercise 2: Create objects using literal notation

Literal notation, sometimes called associative arrays, provides a shorthand way to create objects using JavaScript. Perform these steps:

  1. Create an object using literal notation.
  2. Add a property to the new object.
  3. Add a method to the new object.

Exercise 3: Create objects using the object constructor and prototypes

The most reusable way to create objects in JavaScript is by using the object constructor paired with prototypes. This method of creating objects is completely flexible, allowing you to create unlimited instances of an object rather than only one. Perform these steps:

  1. Create an object using the object constructor and prototypes.
  2. Add a property to the new object.
  3. Add a method to the new object.
  4. Instantiate the object.

Exercise solutions

Follow these solution steps to check your work.


Downloadable resources


Related topics


Comments

Sign in or register to add and subscribe to comments.

static.content.url=http://www.ibm.com/developerworks/js/artrating/
SITE_ID=1
Zone=Web development
ArticleID=768094
ArticleTitle=Practice: Creating objects with JavaScript
publish-date=11012011