Practice: Creating objects with JavaScript
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:
- Create an object using the
Object
function. - Add a property to the new object.
- 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:
- Create an object using literal notation.
- Add a property to the new object.
- 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:
- Create an object using the object constructor and prototypes.
- Add a property to the new object.
- Add a method to the new object.
- Instantiate the object.
Exercise solutions
Follow these solution steps to check your work.
Downloadable resources
Related topics
- To learn more about creating custom objects with JavaScript, read "Get started with object-oriented JavaScript code" (developerWorks, April 2011).
- To learn about JavaScript's existing built-in objects, read "Understanding built-in objects in JavaScript" (developerWorks, August 2011).
- To learn more about the fundamentals of the JavaScript language, check out "Get started with the JavaScript language, Part 1: JavaScript language fundamentals" (developerWorks, April 2011) and "Get started with the JavaScript language, Part 2: Events, cookies, timing, and more" (developerWorks, August 2011).