[ Team LiB ] |
Recipe 12.9 Implementing Subclass Versions of Superclass Methods12.9.1 ProblemYou want to write a subclass implementation of a superclass method (that is, you want a subclass to have a different implementation of a particular method than its superclass). 12.9.2 SolutionAdd a method to the subclass with the same name as the superclass method. If you want to call the superclass method from within the subclass method, use the super keyword to reference the superclass. 12.9.3 DiscussionAlthough a subclass inherits all the methods and properties of a superclass, a subclass does not need to use the superclass implementations. Sometimes, a superclass method may be a generic implementation of particular functionality, and you want to create a more specific implementation within the subclass. When you explicitly define a method within the subclass, the ActionScript interpreter does not search up the prototype chain to find any other versions of that method (the prototype chain is the hierarchy of prototype properties from the subclass up to any superclasses that it inherits from). However, if you want a subclass implementation to call the superclass version of the method, use the super keyword to reference the superclass from within the subclass. For example: // Define a superclass. _global.MySuperClass = function ( ) {}; // Create a superclass implementation of myMethod( ). MySuperClass.prototype.myMethod = function ( ) { return 12; }; // Create a subclass. _global.MySubClass = function ( ) {}; // Define the inheritance for the subclass. MySubClass.prototype = new MySuperClass( ); // Define a subclass implementation of myMethod( ). This effectively obscures the // inherited method of the same name (within the subclass only). However, you can // have the subclass implementation call the superclass version of myMethod( ) using // the super keyword. MySubClass.prototype.myMethod = function ( ) { // Explicitly invoke the superclass implementation of myMethod( ). Invoking the // superclass implementation from within the subclass version of the method is // fairly typical. var superVal = super.myMethod( ); // Return the superclass result plus three. return superVal + 3; }; // Create an instance of MySubClass sub = new MySubClass( ); // Displays: 15 (which is 12 from the superclass plus 3 from the subclass) trace(sub.myMethod( )); 12.9.4 See AlsoFor a detailed discussion of the prototype chain, refer to the "The Almighty Prototype Chain" section of Chapter 12 in ActionScript for Flash MX: The Definitive Guide. That chapter is freely downloadable from http://moock.org/asdg/samples. |
[ Team LiB ] |