216
Functions and Methods
Anonymous functions are often more difficult to read. Compare the following code to the
preceding code.
var myCircle:Function = function(radius:Number):Number {
// function block here
return (Math.PI * radius * radius);
};
trace(myCircle(5));
You can also place functions in class files when you use ActionScript 2.0, as the following
example shows:
class Circle {
public function area(radius:Number):Number {
return (Math.PI * Math.pow(radius, 2));
}
public function perimeter(radius:Number):Number {
return (2 * Math.PI * radius);
}
public function diameter(radius:Number):Number {
return (radius * 2);
}
}
For more information on writing functions in a class file, see
Chapter 7, “Classes,” on
page 225
.
As you can see in the previous code sample, you don’t need to place functions on a timeline.
The following example also puts functions in a class file. This is a good practice to adopt
when you create large applications by using ActionScript 2.0, because it lets you reuse your
code easily in several applications. When you want to reuse the functions in other
applications, you can import the existing class rather than rewrite the code from scratch or
duplicate the functions in the new application.
To create functions in a class file:
1.
Create a new ActionScript document and save it as
Utils.as
.
2.
Type the following ActionScript into the Script pane:
class Utils {
public static function randomRange(min:Number, max:Number):Number {
if (min > max) {
var temp:Number = min;
min = max;
max = temp;
}
return (Math.floor(Math.random() * (max - min + 1)) + min);
}
public static function arrayMin(num_array:Array):Number {
if (num_array.length == 0) {
Summary of Contents for FLASH 8-LEARNING ACTIONSCRIPT 2.0 IN FLASH
Page 1: ...Learning ActionScript 2 0 in Flash...
Page 8: ...8 Contents...
Page 18: ...18 Introduction...
Page 30: ...30 What s New in Flash 8 ActionScript...
Page 66: ...66 Writing and Editing ActionScript 2 0...
Page 328: ...328 Interfaces...
Page 350: ...350 Handling Events...
Page 590: ...590 Creating Interaction with ActionScript...
Page 710: ...710 Understanding Security...
Page 730: ...730 Debugging Applications...
Page 780: ...780 Deprecated Flash 4 operators...
Page 830: ...830 Index...