What is Software? | What is Education? | What is Technology? | What is Research? | What is Wi-Fi? | What is Communication? | What is Customer Service?

Free SEO Tutorials & Help

Tutorials:   Adobe Flash   Adobe Photoshop   CorelDRAW   SEO  

Site Map

Website Development | Cable & Broadband Magazine | Solutions for Higher Education | Auction Anything Online

Adobe Flash Help & Tutorials

 Back to Topics

 

Working with Functions and Methods in Flash

About functions and methods

About types of methods and functions

About built-in and top-level functions

Writing named functions

Writing anonymous and callback functions

About function literals

About constructor functions

Defining global and timeline functions

Targeting and calling user-defined functions

Naming functions

Using functions in Flash

Using variables in functions

Passing parameters to a function

Returning values from functions

About nested functions

Understanding methods

Naming methods

 
About functions and methods

TOP

Methods and functions are blocks of ActionScript code that you can reuse anywhere in a SWF file. You might write your functions in the FLA file or in an external ActionScript file and then call the function from anywhere within your documents. Methods are merely functions that are located within an ActionScript class definition. You can define functions to execute a series of statements on passed values. Your functions can also return values. After a function is defined, it can be called from any timeline, including a timeline of a loaded SWF file.

If you pass values as parameters to a function, the function can perform calculations using the supplied values. Each function has individual characteristics, and some functions require that you pass certain types or numbers of values. If you pass more parameters than the function requires, the function ignores the extra values. If you don't pass a required parameter, the function assigns the undefined data type to the empty parameters. This can cause errors during runtime. A function can also return values.

NOTE : To call a function, that function's definition must be in a frame that the playhead has reached.

You can think of a well-written function as a "black box." If the function contains carefully placed comments about its input, output, and purpose, a person using the function does not need to understand exactly how it works internally.

The basic syntax for a simple named function is:

function traceMe() {

trace("your message");

}

traceMe();

The basic syntax for a simple named function that builds on the previous example by passing a parameter, yourMessage, is:

function traceMe(yourMessage:String) {

trace(yourMessage);

}

traceMe("How you doing?");

Alternatively, if you want to pass multiple parameters, you could use the following code:

var yourName:String = "Ester";

var yourAge:String = "65";

var favSoftware:String = "Flash";

function traceMe(favSoftware:String, yourName:String, yourAge:String) {

trace("I'm " + yourName + ", I like " + favSoftware + ", and I'm " + yourAge + ".");

}

traceMe(favSoftware,yourName,yourAge);

 

About types of methods and functions

TOP

Functions that belong to a class are called the methods of that class. There are several types of functions that you can use in your applications, including built-in functions, named and user-defined functions, anonymous functions, callback functions, constructor functions, and function literals. The following sections contain information on how to define these functions.

You can also write functions in an ActionScript class file. You use these functions as methods in your scripts. In the following example, the Person class displays a constructor method, class methods, instance methods, and accessor methods (getters and setters). The comments in this code sample show where these methods occur in the code.

class Person {

public static var numPeople:Number = 0;

// instance members

private var _speed:Number;

// constructor

public function Person(speed:Number) {

Person.numPeople++;

this._speed = speed;

}

// static methods

public static function getPeople():Number {

return Person.numPeople;

}

// instance methods

public function walk(speed:Number):Void {

this._speed = speed;

}

public function run():Void {

this._speed *= 2;

}

public function rest():Void {

this._speed = 0;

}

// getters/setters (accessor methods)

public function get speed():Number {

return this._speed;

}

}

For a full demonstration of how to write methods like the ones in the previous code sample, see Classes. The methods that you use in your code might belong to a class that is built into the ActionScript language. MovieClip and Math are examples of top-level classes that you might use in an application. When you use methods from these classes in your code, they are functions written in the built-in class (similar to the previous code sample). Alternatively, you could use methods from a custom class that you wrote yourself.

Functions that don't belong to a class are called top-level functions (sometimes called predefined or built-in functions), meaning that you can call them without a constructor. Examples of functions that are built in to the top level of the ActionScript language are trace() and setInterval().

To add a top-level function call to your code, just add a single line of code in the Script pane of the Actions panel. For example, type the following:

trace("my message");

When you test the SWF file with this single line of code, the top-level trace() function is called, and text appears in the Output panel.

Remember: when you want to assign a method to a property, you omit the parentheses after the method name because you're passing a reference to the function:

my_mc.myMethod = aFunction;

However, when you want to invoke a method in your code, you need to include the parentheses following the method name:

my_mc.myMethod();

 

About built-in and top-level functions

TOP

As discussed in About functions and methods, a function is a block of ActionScript code that can be reused anywhere in a SWF file. If you pass values as parameters to a function, the function operates on those values. A function can also return values.

You can use functions that are built into the ActionScript language. They might be top level, as described in About types of methods and functions; or the function might be in a built-in class, such as Math or MovieClip, which you use as a method in your application.

You use built-in functions in ActionScript to perform certain tasks and to access information. For example, you can get the number of milliseconds the SWF file has been playing by using getTimer(). Or you can get the version number of Flash Player that hosts the file by using getVersion(). Functions that belong to an object are called methods. Functions that don't belong to an object are called top-level functions and are found in subcategories of the Global Functions category of the Actions panel.

Some built-in functions require you to pass certain values. If you pass more parameters than the function requires, the extra values are ignored. If you don't pass a required parameter, the empty parameters are assigned the undefined data type, which can cause errors during runtime.

NOTE : To call a function, that function's definition must be in a frame that the playhead has reached.

Top-level functions are easy to use. To call a function, simply use the function name and pass any parameters required by that function. (For information on required parameters, see the entry for the function in the ActionScript 2.0 Language Reference). For example, add the following ActionScript to Frame 1 of the Timeline:

trace("my message");

When you test the SWF file, my message appears in the Output panel. Two other examples of top-level functions are setInterval() and getTimer(). The next example shows how to use both of these functions together. Add the following code to Frame 1 of the Timeline:

function myTimer():Void {

trace(getTimer());

}

var intervalID:Number = setInterval(myTimer, 100);

This code creates a simple timer using getTimer(), and uses the setInterval() and trace() top-level functions to display the number of milliseconds since the SWF file began to play in Flash Player.

 

Writing named functions

TOP

A named function is a kind of function that you commonly create in your ActionScript code to carry out all kinds of actions. When you create a SWF file, the named functions are compiled first, which means that you can reference the function anywhere in your code, as long as the function has been defined in the current or a previous frame. For example, if a function is defined in Frame 2 of a timeline, you cannot access that function in Frame 1 of the timeline.

The standard format for named functions is as follows:

function functionName(parameters) {

// function block

}

This piece of code contains the following parts:

functionName is the unique name of the function. All function names in a document must be unique.

parameters contains one or more parameters that you pass to the function. Parameters are sometimes called arguments.

// function block contains all of the ActionScript code that's carried out by the function. This part contains the statements that "do stuff." You can put the code that you want to execute here. The // function block comment is a placeholder for where your code for the function block would go.

To use a named function:

  1. Create a new document called namedFunc.fla.

  2. Import a short sound file into the library by selecting File > Import > Import to Library and selecting a sound file.

  3. Right-click the sound file and select Linkage.

  4. Type mySoundID in the Identifier text box.

  5. Select Frame 1 of the Timeline and add the following code to the Actions panel:

    function myMessage() {\

    trace("mySoundID completed");

    }

    var my_sound:Sound = new Sound();

    my_sound.attachSound("mySoundID");

    my_sound.onSoundComplete = myMessage;

    my_sound.start();

    In this code you create a named function called myMessage, which you use later in the script to call a trace() function.

  6. Select Control > Test Movie to test the SWF file.

You use the function statement to create your own function in ActionScript. Remember that parameters are optional; however, if you don't have parameters, you still need to include the brackets. The content between the curly braces ({}) is called the function block.

You can write functions on the main timeline or within external ActionScript files, including class files.

You also write constructor functions in class files using this format (however, the name of the function matches the class).

 

Writing anonymous and callback functions

TOP

A named function is a function that you reference in your script before or after you define it, whereas an anonymous function is an unnamed function that references itself; you reference the anonymous function when you create it. When you write ActionScript code, you will create many anonymous functions.

Anonymous functions are commonly used when you work with event handlers. To write an anonymous function, you could store a function literal inside a variable. Therefore, you can reference the function later in your code. The next example shows you how to write an anonymous function.

To write an anonymous function:

  1. Create a movie clip on the Stage, and then select the clip.

  2. Open the Property inspector, and type my_mc into the Instance Name text box.

  3. Select Frame 1 of the Timeline, and type the following code into the Actions panel:

    var myWidth = function () {

    trace(my_mc._width);

    };

    //later in code you can add

    myWidth();

  4. Select Control > Test Movie.

    The width of the movie clip is displayed in the Output panel.

You can also create a function inside an object, such as an XML or LoadVars instance. You can associate an anonymous function with a certain event to create a callback function. A function calls a callback function after a specific event occurs, such as after something finishes loading (onLoad()) or finishes animating (onMotionFinished()).

For example, sometimes you need to write ActionScript to handle data that loads into a SWF file from the server. After you finish loading data into a SWF file, you can access the data from that location. It's important to use ActionScript to check whether the data has been fully loaded. You can use callback functions to send a signal that the data has been loaded into the document.

In the following callback function, in which you load a remote XML document, you associate an anonymous function with the onLoad() event. You use XML.load() and the callback function, as shown in the following example. Type the following code on Frame 1 of the Timeline:

var my_xml:XML = new XML();

my_xml.onLoad = function(success:Boolean):Void {

trace(success);

};

my_xml.load("http://www.helpexamples.com/crossdomain.xml");

You can see from the previous code snippet that the onLoad() event handler uses an anonymous function to handle the onLoad() event.

You could also use anonymous functions with the setInterval() function, as seen in the following code, which uses setInterval() to call the anonymous function approximately every 1000 milliseconds (1 second):

setInterval(function() {trace("interval");}, 1000);

You can use named functions instead of anonymous functions. Named functions are often easier to read and understand (except in some circumstances, such as callback functions). You can also forward-reference a named function, which means you reference it before the function exists on a timeline.

You cannot reference an anonymous function anywhere in your code (unless you assign it to a variable), as you can when you use a named function. For example, suppose that you have anonymous functions on Frame 5 of your FLA file, such as the following:

//with a movie clip called my_mc that spans the timeline

stop();

var myWidth = function () {

trace(my_mc._width);

};

If you place the following code on Frame 1, it cannot reference the function:

myWidth();

Similarly, the following code placed on any frame does not work:

myWidth();

var myWidth:Function = function () {

trace(my_mc._width);

};

However, this code works properly:

var myWidth:Function = function () {

trace(my_mc._width);

};

myWidth();

NOTE : You could also place myWidth() on any frame that is after the frame that contains the myWidth function.

When defining a named function, calling it in a frame script works, even though the equivalent code with an anonymous function does not work:

// the following does work because you are calling a named function:

myWidth();

function myWidth() {

trace("foo");

}

// the following does not work because you are calling an anonymous function:

myWidth();

var myWidth:Function = function () {

trace("foo");

};

 

About function literals

TOP

A function literal is an unnamed function that you declare in an expression instead of in a statement. Function literals are useful when you need to use a function temporarily or to use a function in your code where you might use an expression instead. The syntax for a function literal is:

function (param1, param2, etc) {

// statements

};

For example, the following code uses a function literal as an expression:

var yourName:String = "Ester";

setInterval(function() {trace(yourName);}, 200);

NOTE : When you redefine a function literal, the new function definition replaces the old definition.

 

About constructor functions

TOP

The constructor of a class is a special function that is called automatically when you create an instance of a class by using the new keyword (such as, var my_xml:XML = new XML();). The constructor function has the same name as the class that contains it. For example, a custom Person class that you create would contain the following constructor function:

public function Person(speed:Number) {

Person.numPeople++;

this._speed = speed;

}

Then you could create a new instance by using:

var myPerson:Person = new Person();

NOTE : If you do not explicitly declare a constructor function in your class file--that is, if you don't create a function whose name matches that of the class--the compiler automatically creates an empty constructor function for you.

A class can contain only one constructor function; overloaded constructor functions are not allowed in ActionScript 2.0. Also, a constructor function cannot have a return type.

 

Defining global and timeline functions

TOP

In About functions and methods, you explored the different kinds of functions that are available in Flash. As with variables, functions are attached to the timeline of the movie clip that defines them, and you must use a target path to call them. As with variables, you can use the _global identifier to declare a global function that is available to all timelines and scopes without using a target path. To define a global function, precede the function name with the identifier _global, as shown in the following example:

_global.myFunction = function(myNum:Number):Number {

return (myNum * 2) + 3;

};

trace(myFunction(5)) // 13

For information on _global and scope, About variables and scope.

To define a timeline function, use the function statement followed by the name of the function, any parameters to be passed to the function, and the ActionScript statements that indicate what the function does.

The following example is a function named areaOfCircle with the parameter radius:

function areaOfCircle(radius:Number):Number {

return (Math.PI * radius * radius);

}

trace(areaOfCircle(8));

 

Targeting and calling user-defined functions

TOP

User-defined functions are simply functions that you create yourself to use in applications, as opposed to functions in built-in classes that perform predefined functions. You name the functions yourself and add statements in the function block. Previous sections cover writing functions such as named, unnamed, and callback functions. For information on naming functions, see Naming functions, and for information on using functions, see Using functions in Flash.

You can use a target path to call a function in any timeline from any timeline, including from a timeline of a loaded SWF file. To call a function, type the target path to the name of the function, if necessary, and pass any required parameters inside parentheses. There are several forms of syntax for user-defined functions. The following code uses a path to call the initialize() function, which was defined on the current timeline and requires no parameters:

this.initialize();

The following example uses a relative path to call the list() function, which was defined in the functionsClip movie clip:

this._parent.functionsClip.list(6);

You can also define your own named functions. For example, the following named function helloWorld() is user defined:

function helloWorld() {

trace("Hello world!");

};

The following example shows you how to use a user-defined function in a FLA file.

To create and call a simple user-defined function:

  1. Create a new Flash document and save it as udf.fla.

  2. Add the following ActionScript to Frame 1 of the main Timeline:

    function traceHello(name:String):Void {

    trace("hello, " + name + "!");

    }

    traceHello("world"); // hello, world!

    The previous code creates a user-defined function named traceHello() that takes one argument, name, and traces a greeting message. To call the user-defined function, you can call traceHello from the same timeline as the function definition and pass a single string value.

  3. Select Control > Test Movie to test the Flash document.

     

Naming functions

TOP

Function names should start with a lowercase letter. Your function names should describe the value the function returns, if any. For example, if the function returns the title of a song, you might name it getCurrentSong().

Establish a standard for grouping similar functions (functions that relate to each other based on functionality), because ActionScript does not permit overloading. In the context of object-oriented programming (OOP), overloading refers to the ability to make your functions behave differently depending on what data types are passed into them.

As with variables, you cannot use special characters, and the method name cannot start with a number.

 

Using functions in Flash

TOP

This section shows you how to use functions in an application. Some of the following code examples use ActionScript that resides in the FLA file, and other code examples place functions in a class file for comparison.

To reduce the amount of work you have to do, as well as the size of your SWF file, try to reuse blocks of code whenever possible. One way you can reuse code is by calling a function multiple times instead of creating different code each time. Functions can be generic pieces of code; you can use the same blocks of code for slightly different purposes in a SWF file. Reusing code lets you create efficient applications and minimizes the ActionScript code that you must write, which reduces development time.

You can create functions in a FLA file or a class file or write ActionScript code that resides in a code-based component. The following examples show you how to create functions on a timeline and in a class file.

TIP : By packing your code into class files or code-based components, you can easily share, distribute, or reuse blocks of code. Users can install your component, drag it onto the Stage, and use the code that you store in the file, such as the workflow for code-based components available in Flash (Window > Common Libraries > Classes).

The following example shows you how to create and call a function in a FLA file.

To create and call a function in a FLA file:

  1. Create a new Flash document and save it as basicFunction.fla.

  2. Select Window > Actions to open the Actions panel.

  3. Type the following ActionScript code into the Script pane:

    function helloWorld(){

    // statements here

    trace("Hello world!");

    };

    This ActionScript defines the (user-defined, named) function called helloWorld(). If you test your SWF file at this time, nothing happens. For example, you don't see the trace statement in the Output panel. To see the trace statement, you have to call the helloWorld() function.

  4. Type the following line of ActionScript code after the function:

    helloWorld();

    This code calls the helloWorld() function.

  5. Select Control > Test Movie to test the FLA file.

    The following text is displayed in the Output panel: Hello world!

There are several different ways that you can write functions on the main timeline. Most notably, you can use named functions and anonymous functions. For example, you can use the following syntax when you create functions:

function myCircle(radius:Number):Number {

return (Math.PI * radius * radius);

}

trace(myCircle(5));

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);

}

}

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) {

    return Number.NaN;

    }

    num_array.sort(Array.NUMERIC | Array.DESCENDING);

    var min:Number = Number(num_array.pop());

    return min;

    }

    public static function arrayMax(num_array:Array):Number {

    if (num_array.length == 0) {

    return undefined;

    }

    num_array.sort(Array.NUMERIC);

    var max:Number = Number(num_array.pop());

    return max;

    }

    }

  3. Select File > Save to save the ActionScript file.

  4. Create a new Flash document and save it as classFunctions.fla in the same directory as Utils.as.

  5. Select Window > Actions to open the Actions panel.

  6. Type the following ActionScript into the Script pane:

    var randomMonth:Number = Utils.randomRange(0, 11);

    var min:Number = Utils.arrayMin([3, 3, 5, 34, 2, 1, 1, -3]);

    var max:Number = Utils.arrayMax([3, 3, 5, 34, 2, 1, 1, -3]);

    trace("month: " + randomMonth);

    trace("min: " + min); // -3

    trace("max: " + max); // 34

  7. Select Control > Test Movie to test the documents. The following text is displayed in the Output panel:

    month: 7

    min: -3

    max: 34

 

Using variables in functions

TOP

Local variables are valuable tools for organizing code and making it easy to understand. When a function uses local variables, it can hide its variables from all other scripts in the SWF file; local variables are invoked in the scope of the body of the function and cease to exist when the function exits. Flash also treats any parameters passed to a function as local variables.

NOTE : You can also use regular variables in a function. However, if you modify regular variables, it is good practice to use script comments to document these modifications.

To use variables in functions:

  1. Create a new Flash document and save it as flashvariables.fla.

  2. Add the following ActionScript to Frame 1 of the main Timeline:

    var myName:String = "Ester";

    var myAge:String = "65";

    var myFavSoftware:String = "Flash";

    function traceMe(yourFavSoftware:String, yourName:String, yourAge:String) {

    trace("I'm " + yourName + ", I like " + yourFavSoftware + ", and I'm " + yourAge + ".");

    }

    traceMe(myFavSoftware, myName, myAge);

  3. Select Control > Test Movie to test the Flash document.

 

Passing parameters to a function

TOP

Parameters, also referred to as arguments, are the elements on which a function executes its code. (In this book, the terms parameter and argument are interchangeable.) You can pass parameters (values) to a function. You can then use these parameters for processing the function. You use the values within the function block (statements within the function).

Sometimes parameters are required, and sometimes they are optional. You might even have some required and some optional parameters in a single function. If you do not pass enough parameters to a function, Flash sets the missing parameter values to undefined, which may cause unexpected results in your SWF file.

The following function called myFunc() takes the parameter someText:

function myFunc(someText:String):Void {

trace(someText);

}

After passing the parameter, you can pass a value to the function when you call the function. This value traces in the Output panel, as follows:

myFunc("This is what traces");

When you call the function, you should always pass the specified number of parameters unless your function checks for undefined values and sets default values accordingly. The function substitutes the passed values for the parameters in the function definition; if any parameters are missing, Flash sets their value to undefined. You regularly pass parameters into functions when you write ActionScript code.

You can also pass multiple parameters to a function, which can be as simple as the following:

var birthday:Date = new Date(1901, 2, 3);

trace(birthday);

Each parameter is separated by a comma delimiter. Many built-in functions in the ActionScript language have multiple parameters. For example, the startDrag() method of the MovieClip class takes five parameters, lockCenter, left, top, right, and bottom:

startDrag(lockCenter:Boolean, left:Number, top:Number, right:Number, bottom:Number):Void

To pass a parameter to a function:

  1. Create a new Flash document and save it as parameters.fla.

  2. Add the following code to Frame 1 of the Timeline:

    function traceMe(yourMessage:String):Void {

    trace(yourMessage);

    }

    traceMe("How are you doing?");

    The first few lines of code create a user-defined function called traceMe(), which takes a single parameter, yourMessage. The last line of code calls the traceMe() function and passes the string value "How are you doing?".

  3. Select Control > Test Movie to test the Flash document.

    The next example demonstrates how to pass multiple parameters to a function.

To pass multiple parameters to a function:

  1. Create a new Flash document and save it as functionTest.fla.

  2. Add the following code to Frame 1 of the main Timeline:

    function getArea(width:Number, height:Number):Number {

    return width * height;

    }

    The getArea() function takes two parameters, width and height.

  3. Type the following code after the function:

    var area:Number = getArea(10, 12);

    trace(area); // 120

    The getArea() function call assigns the values 10 and 12 to the width and height, respectively, and you save the return value in the area instance. Then you trace the values that you save in the area instance.

  4. Select Control > Test Movie to test the SWF file.

    You see 120 in the Output panel.

    The parameters in the getArea() function are similar to values in a local variable; they exist while the function is called and cease to exist when the function exits.

In the next example, the ActionScript returns the value NaN (not a number) if you don't pass enough parameters to the addNumbers() function.

To pass a variable number of parameters to a function:

  1. Create a new Flash document and save it as functionTest2.fla.

  2. Add the following code to Frame 1 of the main Timeline:

    function addNumbers(a:Number, b:Number, c:Number):Number {

    return (a + b + c);

    }

    trace(addNumbers(1, 4, 6)); // 11

    trace(addNumbers(1, 4)); // NaN (Not a Number), c equals undefined

    trace(addNumbers(1, 4, 6, 8)); // 11

    If you don't pass enough parameters to the addNumbers function, the missing arguments are assigned a default value of undefined. If you pass too many parameters, the excess parameters are ignored.

  3. Select Control > Test Movie to test the Flash document.

    Flash displays the following values: 11, NaN, 11.

 

Returning values from functions

TOP

You use the return statement to return values from functions. The return statement specifies the value that is returned by a function. The return statement returns the result of an evaluation as a value of the function in which an expression executes. The return statement returns its result immediately to the calling code.

The following rules govern how to use the return statement in functions:

  • If you specify a return type other than Void for a function, you must include a return statement and it must be followed by the returned value in the function.

  • If you specify a return type of Void, you do not need to include a return statement, but if you do, it must not be followed by any value.

  • Regardless of the return type, you can use a return statement to exit from the middle of a function.

  • If you don't specify a return type, including a return statement is optional.

For example, the following function returns the square of the parameter myNum and specifies that the returned value must be a Number data type:

function sqr(myNum:Number):Number {

return myNum * myNum;

}

Some functions perform a series of tasks without returning a value. The next example returns the processed value. You are capturing that value in a variable, and then you can use that variable within your application.

To return a value and capture it in a variable:

  1. Create a new Flash document and save it as return.fla.

  2. Add the following code to Frame 1 of the main Timeline:

    function getArea(width:Number, height:Number):Number {

    return width * height;

    }

    The getArea() function takes two parameters, width and height.

  3. Type the following code after the function:

    var area:Number = getArea(10, 12);

    trace(area); // 120

    The getArea() function call assigns the values 10 and 12 to the width and height, respectively, and you save the return value in the area instance. Then you trace the values that you save in the area instance.

  4. Select Control > Test Movie to test the SWF file.

    You see 120 in the Output panel.

    The parameters in the getArea() function are similar to values in a local variable; they exist while the function is called and cease to exist when the function exits.

 

About nested functions

TOP

You can call a function from inside another function. This lets you nest functions so that you can have them perform specific tasks in Flash.

For example, you can nest functions on a timeline to perform specific tasks on a string. Type the following code on Frame 1 of the Timeline:

var myStr:String = "My marshmallow chicken is yellow.";

trace("Original string: " + myStr);

function formatText():Void {

changeString("Put chicken in microwave.");

trace("Changed string: " + myStr);

}

function changeString(newtext:String):Void {

myStr = newtext;

}

// Call the function.

formatText();

Select Control > Test Movie to test the nested function. The formatText() and changeString() functions are both applied to the string when you call the formatText() function.

Understanding methods

TOP

Methods are functions that are associated with a class. The class could be a custom class or built-in classes that are part of the ActionScript language. For information on comparing methods to functions, see About functions and methods and About types of methods and functions.

For example, sortOn() is a built-in method associated with the Array class (sortOn is a function of the predefined Array class built into Flash).

To use the sortOn() method in a FLA file:

  1. Create a new Flash document and save it as methods.fla.

  2. Add the following code to Frame 1 of the Timeline:

    var userArr:Array = new Array();

    userArr.push({firstname:"George", age:39});

    userArr.push({firstname:"Dan", age:43});

    userArr.push({firstname:"Socks", age:2});

    userArr.sortOn("firstname");

    var userArrayLenth:Number = userArr.length;

    var i:Number;

    for (i = 0; i < userArrayLenth; i++) {

    trace(userArr[i].firstname);

    }

    You use the sortOn() method of the Array class to create a new Array object named userArr. The array is populated by three objects that contain a first name and age, and then the array is sorted based on the value of each object's firstname property. Finally, you loop over each item in the array and display the first name in the Output panel and sort the names alphabetically by first letter.

  3. Select Control > Test Movie to test the SWF file.

    This code displays the following in the Output panel:

    Dan

    George

    Socks

As demonstrated in Writing named functions, when you write the following code on Frame 1 of the Timeline, your ActionScript code defines a function called eatCabbage().

function eatCabbage() {

trace("tastes bad");

}

eatCabbage();

However, if you write the eatCabbage() function within a class file and, for example, call eatCabbage() in the FLA file, then eatCabbage() is considered to be a method.

The next examples show you how to create methods within a class.

To compare methods and functions:

  1. Create a new ActionScript file, select File > Save As, and save it as EatingHabits.as.

  2. Type the following ActionScript code in the Script window:

    class EatingHabits {

    public function eatCabbage():Void {

    trace("tastes bad");

    }

    }

  3. Save your changes to EatingHabits.as.

  4. Create a new Flash document, select File > Save As, name it methodTest.fla, and save this file in the same directory as EatingHabits.as.

  5. Type the following ActionScript code onto Frame 1 of the Timeline:

    var myHabits:EatingHabits = new EatingHabits();

    myHabits.eatCabbage();

    When you use this ActionScript, you are calling the eatCabbage() method of the EatingHabits class.

    NOTE : When you use methods of any built-in class (in addition to the custom class you wrote earlier in this procedure), you are using a method on a timeline.

  6. After the previous line of ActionScript, add the following code:

    function eatCarrots():Void {

    trace("tastes good");

    }

    eatCarrots();

    In this code, you write and call the eatCarrots() function.

  7. Select Control > Test Movie to test the SWF file.

 

Naming methods

TOP

You should use verbs to name methods, and words with mixed cases for concatenated words, making sure that the first letter is lowercase. For example, you might name methods in the following ways:

sing();

boogie();

singLoud();

danceFast();

You use verbs for most method names because methods perform an operation on an object. As with variables, you cannot use special characters, and the method name cannot start with a number.

 

Copyright ADOBE - All Rights Reserved Worldwide

 

 

More Topics:

Working with Flash Documents

How to work in Flash WorkSpace

Working with Projects in Flash

Process to Build your First Application in Flash

Using Symbols, Instances and Library Assets in Flash

How to Build Video Player in Flash

How to Work with Color, Strokes and Fills in Flash

How to Create Document in Flash

What is Vector and Bitmap Graphics in Flash

How to Create a Banner in Flash, Part 1

How to Work with Text in Flash

How to Create a Banner in Flash, Part 2

How to Use Imported Artwork in Flash

How to Create a Banner in Flash, Part 3

How to Work with Graphic Objects in Flash

How to Work with Layers in Flash

How to Use Filters and Blends

Working with Graphics in Flash

What is Accessibility Features in Flash

How to Create Motion (Shape Tween & Motion Tween) in Flash

How to Create an Application in Flash

What is Masking in Flash

How to Work with Video in Flash

How to Use Layout Tools in Flash

What are Behaviors in Flash

How to Work with Sound in Flash

How to Create Symbols and Instances in Flash

What is ActionScript in Flash

How to Write ActionScript With Script Assist in Flash

How to Add Button Animation and Navigation in Flash

What is Data Integration in Flash

How to Work with Screens

How to Create a Presentation with Screens

What is Extending Flash

How to Create Multilanguage Text in Flash

How to Create Graphics: Draw in Flash

What is Flash Lite

Ways of Data Integration

How to Create Graphics: Create a Timeline Animation in Flash

Getting Started with Flash Lite in Flash

How to Publish Flash Documents

How to Create Graphics: Making Animations with Easing

Learning Flash Lite 1.X ActionScript in Flash

How to Export Flash Content and Images from Flash

How to Create Graphics: Applying Gradients in Flash

Process of Writing and Editing ActionScript 2.0 in Flash

How to Create Accessible Content in Flash

How to Create Graphics: Apply Graphic Filters and Blends

What is Data and Data Types in Flash

Process of Printing from SWF Files in Flash

Using ActionScript: How to Use Script Assist mode in Flash

Learn Syntax and Language Fundamentals in Flash

How to Create E-learning Content in Flash

Using ActionScript: How to Write Scripts in Flash

Working with Functions and Methods in Flash

Process of Using Templates in Flash

Using ActionScript: Process of Adding Interactivity in Flash

What are Classes in Flash

Control Tag Summary of XML to UI in Flash

Using ActionScript: How to Create a Form with Conditional Logic and Send Data in Flash

What is Inheritance in Flash

What is Data Integration: Overview

Using ActionScript: How to Work with Objects and Classes in Flash

Overview on Interfaces in Flash

What is Data Integration: Using XML for a Timesheet

How to Work with Text and Strings in Flash

How to use Handling Events in Flash

What is Data Integration: Using XUpdate to Update the Timesheet

Learning Animation, Filters and Drawings in Flash

How to Work with Movie Clips in Flash

How to Create Interaction with ActionScript in Flash

How to Work with Images, Sound, and Video in Flash

How to Work with External Data in Flash

What is Security in Flash

How to Debug Applications in Flash

List of Error Messages in Flash

Using Object-Oriented Programming with ActionScript 1.0 in Flash

How to Write Scripts for Earlier Versions of Flash Player in Flash

List of all Keyboard Keys and Key Code Values for using in Flash

Terminology

Introduction to Components in Flash

What are Components in Flash

How to Create an Application with Components

How to Work with Components in Flash

How to Handle Component Events in Flash

How to Customize Components in Flash

How to Create Components in Flash

What is Collection Properties in Flash