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

Using Prototype Objects to Augment Classes

We've learned that ActionScript defines a special static variable named prototype on every function. Using the prototype variable of a given function, we can share information and behavior among all objects created from that function.

Just as ActionScript defines a prototype variable on every function, it also defines a static prototype variable on every class. Using the static prototype variable, we can add shared information and behavior to all instances of a given class at runtime.

For example, the following code defines a new dynamic instance variable, isEmpty, on the built-in String class's prototype object and assigns that variable a function. The function returns true when a string has no characters in it; otherwise the function returns false:

String.prototype.isEmpty = function () {
  return (this == "") ? true : false;
};

To invoke the function isEmpty( ) on a String object, we use the following code:

var s1:String = "Hello World";
var s2:String = "";

trace(s1.isEmpty());  // Displays: false
trace(s2.isEmpty());  // Displays: true

However, the previous code example—and this entire technique—has a problem: the dynamic instance variable isn't added until runtime; therefore, the compiler has no idea that it exists and will generate an error if it is used in strict mode. For example, in strict mode, the code in the preceding example yields this error:

Call to a possibly undefined method isEmpty through a reference with static
type String.

In order ...

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