O'Reilly logo

Essential ActionScript 3.0 by Colin Moock

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

Dynamically Adding New Behavior to an Instance

Having just learned how to create dynamic instance variables, you might wonder whether ActionScript also supports dynamic instance methods—adding a new instance method to a single, specific object without adding it to any other instances of that object's class. In fact, there is no formal means of adding a true instance method to an object dynamically. However, by assigning a function closure to a dynamic instance variable, we can emulate the effect of giving an individual object a new method (for a refresher on the term function closure, see Chapter 5). The following code demonstrates the general approach:

someObject.someDynamicVariable = someFunction;

In the preceding code, someObject is an instance of a dynamic class, someDynamicVariable is the name of a dynamic instance variable (which can be a new variable or an existing variable), and someFunction is a reference to a function closure. Typically, someFunction is supplied using a function literal, as shown in the following code:

someObject.someDynamicVariable = function (param1, param2, ...paramn) {
  // Function body
}

Once someFunction has been assigned to the dynamic instance variable, it can be invoked through the object, exactly like a regular instance method, as shown in the following code:

someObject.someDynamicVariable(value1, value2, ...valuen);

To demonstrate the preceding generic syntax, let's return to the info example from the preceding section:

var info:Object = new Object(); ...

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