dynamic statement

dynamic class className [ extends superClass ] [ implements interfaceName[, interfaceName... ] ] {
 // class definition here 
}

Specifies that objects based on the specified class can add and access dynamic properties at runtime.

Type checking on dynamic classes is less strict than type checking on nondynamic classes, because members accessed inside the class definition and on class instances are not compared with those defined in the class scope. Class member functions, however, can still be type checked for return type and parameter types. This behavior is especially useful when you work with MovieClip objects, because there are many different ways of adding properties and objects to a movie clip dynamically, such as MovieClip.createEmptyMovieClip() and MovieClip.createTextField().

Subclasses of dynamic classes are also dynamic.

Be sure to specify the type when declaring an object, as in the following:

var x:MyClass = new MyClass();

If you do not specify the type when declaring an object (as in the following) then the object is considered dynamic:

var x = new MyClass();

Availability: ActionScript 2.0; Flash Player 6

Example

In the following example, class Person2 has not yet been marked as dynamic, so calling an undeclared function on it generates an error at compile time:

class Person2 { 
 var name:String; 
 var age:Number; 
 function Person2(param_name:String, param_age:Number) { 
 trace ("anything"); 
 this.name = param_name; 
 this.age = param_age; 
 } 
}

In a FLA or AS file that's in the same directory, add the following ActionScript to Frame 1 on the Timeline:

// Before dynamic is added 
var craig:Person2 = new Person2("Craiggers", 32); 
for (i in craig) { 
 trace("craig." + i + " = " + craig[i]); 
} 
/* output:
craig.age = 32 
craig.name = Craiggers */

If you add an undeclared function, dance , an error is generated, as shown in the following example:

trace(""); 
craig.dance = true; 
for (i in craig) { 
 trace("craig." + i + " = " + craig[i]); 
} 
/* output: **Error** Scene=Scene 1, layer=Layer 1, frame=1:Line 14: There is no property with the name 'dance'. craig.dance = true; Total ActionScript Errors: 1 Reported Errors: 1 */

Add the dynamic keyword to the Person2 class, so that the first line appears as follows:

dynamic class Person2 { 

Test the code again, and you see the following output:

craig.dance = true craig.age = 32 craig.name = Craiggers

See also

class statement


Flash CS3