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
prototypeproperty.Add methods and properties to the
prototypeproperty.
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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access