Recipe 12.9 Implementing Subclass Versions of Superclass Methods

12.9.1 Problem

You 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 Solution

Add 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 Discussion

Although 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 Also

For 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.



ActionScript Cookbook
ActionScript 3.0 Cookbook: Solutions for Flash Platform and Flex Application Developers
ISBN: 0596526954
EAN: 2147483647
Year: 2005
Pages: 425

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net