Chapter 8. Custom Objects

The built-in objects discussed in Lesson 7 go a long way in making applications easier to write and maintain, but they stop short of allowing developers to tailor objects to their personal needs and those of their applications. For example, what if it were your job to write an application that emulates a two-dimensional Cartesian coordinate plane? How would the Array, Date, Number, and String data types help you achieve that goal? It could be done, but it would take a lot of time and effort to write a proper application.

The fact is that JavaScript or any object-oriented programming language for that matter wouldn't be useful without the capability to create objects other than the built-in objects provided by the language. Being able to build your own objects and data types makes it possible to write flexible and maintainable applications.

At the heart of JavaScript's object-oriented design is the Object data type. It's the basis of all objects and reference types in JavaScript, and you'll look at how to use it in this lesson.


There are two ways to create a basic object. The first is to use the Object data type's constructor, like this:

var coordinates = new Object();

This code calls the Object() constructor using the new keyword and assigns it to the coordinates variable. As with the Array data type, there is a much simpler (and preferred) way to create an object, by using object literal notation:

var coordinates = {};

Object literal notation ...

Get JavaScript® 24-Hour Trainer now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.