Creating properties dynamically

Another advantage of using prototype objects to implement inheritance is that properties and methods that are added to a prototype object are automatically available to object instances. This is true even if an object instance was created before the properties or methods were added.

In the following example, the color property is added to the prototype object of a Car class after an object instance of Car has already been created.

function Car(make, model) { // define a Car class
   this.make = make;
   this.model = model;
}
var myCar = new Car("Subaru", "Forester"); // create an object instance

trace(myCar.color); // returns undefined

// add the color property to the Car class after myCar was initialized
Car.prototype.color = "blue";

trace(myCar.color); // returns "blue"

You can also add properties to object instances after the instances have been created. When you add a property to a specific object instance, that property is available only to that specific object instance. Using the myCar object instance created previously, the following statements add the color property to myCar after it has already been created.

trace(myCar.color); // returns undefined

myCar.color = "blue"; // add the color property to the myCar instance

trace(myCar.color); // returns "blue"

var secondCar = new Car("Honda", "Accord"); // create a second object instance

trace(secondCar.color); // returns undefined

 

Send me an e-mail when comments are added to this page | Comment Report

Current page: http://livedocs.adobe.com/director/mx2004/release_update_en/01b_wr45.htm