O'Reilly logo

JavaScript & DHTML Cookbook by Danny Goodman

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Creating a Custom Object

NN 3, IE 4

Problem

You want to create a custom object for your data structure.

Solution

As with creating arrays, object creation has both a long form and a compact form. The long form requires that you define a constructor function, while the compact form uses special inline symbols to denote the structure of the object.

A constructor function looks like any other JavaScript function, but its purpose is to define the initial structure of an object—it's property and method names—and perhaps to populate some or all of the properties with initial values. Values to be assigned to properties of the object are typically passed as parameters to the function, and statements in the function assign those values to properties. The following constructor function defines an object with two properties:

function coworker(name, age) {
    this.name = name;
    this.age = age;
}

To create objects with this constructor, invoke the function with the new keyword:

var emp1 = new coworker("Alice", 23);
var emp2 = new coworker("Fred", 32);

The this keyword in the constructor function localizes the context of the function to the object being created. As the function is reused for each object it creates, the context limits itself just to the one object under construction.

If you prefer not to use a constructor function, you can create objects with a shortcut syntax (Version 4 browsers or later) that defines an object inside curly braces. Property names and values are defined inside the ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required