
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
Augmenting Built-in Classes and Objects
|
201
Augmenting Built-in Classes and Objects
In the previous section we learned how to subclass a built-in class. New properties
and methods can also be added directly to an existing built-in class, without sub-
classing it. However, the technique uses an old-school ActionScript 1.0 hack, is
heavy-handed, and requires that we break the important OOP precept that warns us
to keep method and property definitions contained within a class definition. Never-
theless, it does work and can be convenient if used sparingly and prudently.
Here’s the general syntax for adding a new method to a built-in class at runtime:
ClassName.prototype.methodName = function (param1, param2, ...paramn) {
statements
};
Here’s the general syntax for adding a new property to a built-in class at runtime:
ClassName.prototype.propertyName = value;
For example, the following code adds a new method, isEmpty( ), to the built-in String
class. The isEmpty( ) method returns
true when a string has no characters in it; oth-
erwise,
false:
String.prototype.isEmpty = function ( ) {
return (this == "") ? true : false;
};
// Usage example:
var s1:String = "Hello World";
var s2:String = "";
trace(s1.isEmpty( )); // Displays: false
trace(s2.isEmpty( )); // Displays: true
However, the previous code