12.8. Creating Subclasses
Problem
You want to create a subclass that inherits from a superclass.
Solution
Define a new class and set the
new
class’s prototype
property to an
instance of the superclass.
Discussion
A subclass
is a class that has
its
own methods and properties but also uses the methods and properties
of another class (its superclass
). For example,
all the built-in ActionScript classes, such as the
Date
and TextField
classes,
are subclasses of the top-level Object
superclass. You can create a subclass that inherits all the
properties and methods of a superclass by assigning a new instance of
the superclass to the subclass’s
prototype
property. For example:
MySubClass.prototype = new MySuperClass( );
Warning
Assigning a new instance of the superclass to the
subclass’s prototype
wipes out
any existing methods or properties of that prototype. You must assign
the value to prototype
before you add any methods
or properties to the subclass.
This is the correct order in which to perform the actions:
Define the constructor method for the subclass.
Assign inheritance (i.e., the superclass) to the
prototype
property.Add methods and properties to the
prototype
property.
Here is a example of the correct order in which to perform the actions:
_global.MySubClass = function ( ) {}; MySubClass.prototype = new MySuperClass( ); MySubClass.prototype.methodA = function ( ) {}; MySubClass.prototype.myProperty = "some property value";
The following is incorrect! Because the inheritance is defined ...
Get Actionscript Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.