| < Day Day Up > |
6.7 Augmenting Built-in Classes and Objects
In the previous section we learned how to subclass a built-in class. New properties and
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
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 example ”and this entire technique ”has a problem: the newly defined method or property isn't added until runtime; therefore, the compiler has no idea that the new member exists and will generate an error if it is used with typed data. For example, the code in the
There is no method with the name 'isEmpty'.
To avoid this problem, we're forced into a nasty, hacked solution. We
Here's an excerpt from a modified version of the String.as intrinsic class definition. It shows only the new method and doesn't show the rest of the intrinsic class definition:
//***********************************************************************
// ActionScript Standard Library
// String object
//***********************************************************************
intrinsic class String
{
// We add this line to the file so that the compiler
// knows about our new
isEmpty( )
method
function isEmpty( ):Boolean;
}
The
String.as
fix itself has a problem: it must be implemented on every computer that uses the
String.isEmpty( )
method. That is, if you fix the
String.as
file on your work computer and then take your work home, you'll have to fix it on your home computer too. This makes the source code distribution for any application that uses
String.isEmpty( )
very
|
| < Day Day Up > |