Learning ActionScript 2.0 in Adobe Flash |
|
|
|
| Best Practices and Coding Conventions for ActionScript 2.0 > ActionScript coding conventions > Structuring a class file > About the super prefix | |||
If you refer to a method in the parent class, prefix the method with super so that other developers know from where the method is invoked. The following ActionScript 2.0 snippet demonstrates the use of proper scoping by using the super prefix:
In the following example, you create two classes. You use the super keyword in the Socks class to call functions in the parent class (Clothes). Although both the Socks and Clothes classes have a method called getColor(), using super lets you specifically reference the base class's methods and properties. Create a new AS file called Clothes.as, and enter the following code:
class Clothes {
private var color:String;
function Clothes(paramColor) {
this.color = paramColor;
trace("[Clothes] I am the constructor");
}
function getColor():String {
trace("[Clothes] I am getColor");
return this.color;
}
function setColor(paramColor:String):Void {
this.color = paramColor;
trace("[Clothes] I am setColor");
}
}
Create a new class called Socks that extends the Clothes class, as shown in the following example:
class Socks extends Clothes {
private var color:String;
function Socks(paramColor:String) {
this.color = paramColor;
trace("[Socks] I am the constructor");
}
function getColor():String {
trace("[Socks] I am getColor");
return super.getColor();
}
function setColor(paramColor:String):Void {
this.color = paramColor;
trace("[Socks] I am setColor");
}
}
Then create a new AS or FLA file and enter the following ActionScript in the document:
import Socks;
var mySock:Socks = new Socks("maroon");
trace(" -> "+mySock.getColor());
mySock.setColor("Orange");
trace(" -> "+mySock.getColor());
The following result is displayed in the Output panel:
[Clothes] I am the constructor [Socks] I am the constructor [Socks] I am getColor [Clothes] I am getColor -> maroon [Socks] I am setColor [Socks] I am getColor [Clothes] I am getColor -> Orange
If you forgot to put the super keyword in the Socks class's getColor() method, the getColor() method could call itself repeatedly, which would cause the script to fail because of infinite recursion problems. The Output panel would display the following error if you didn't use the super keyword:
[Socks] I am getColor [Socks] I am getColor ... [Socks] I am getColor 256 levels of recursion were exceeded in one action list. This is probably an infinite loop. Further execution of actions has been disabled in this SWF file.
|
|
|
|