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

Customizing an Object's Prototype

NN 4, IE 4

Problem

You want add a property or method to objects that have already been created or are about to be created.

Solution

To add a property or method to a group of objects built from the same constructor, assign the property or method name and its default value to the prototype property of the object. To demonstrate this concept, we'll start with the coworker object constructor from Recipe 3.8 and create four instances of this object, all stored in an array:

function coworker(name, age) {
    this.name = name;
    this.age = age || 0;
    this.show = showAll;
}
var employeeDB = new Array( );
employeeDB[employeeDB.length] = new coworker("Alice", 23);
employeeDB[employeeDB.length] = new coworker("Fred", 32);
employeeDB[employeeDB.length] = new coworker("Jean", 28);
employeeDB[employeeDB.length] = new coworker("Steve", 24);

Each object has two properties and one method assigned to it. Each object's property values are private to that particular object instance. And, although each object shares a method name (and the same function code for that method), when the method executes, it does so within the private context of the single object's instance (e.g., the this keyword in the method code refers to the object instance only).

Before or after the object instances exist, you can add a property that belongs to the prototype—an abstract object that represents the "mold" from which the object instances are made. When you assign a property and value to 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