Functions or methods are block of ActionScript statements which can be reused. The functions can take one or more parameters and return one value. A function can be reused anywhere in an SWF file. ActionScript is having a collection of built in functions. Also if required we developers can also create custom ActionScript functions.
The general form of a method is
function functionName(parameter-list) {
//body of method
}
Defining a function
We need to use the function keyword for defining a function. The syntax of a function definition is as follows.
function functionName(parameter1, paramater2 , .....) {
function body
}
For eg:
function sayHello(){
trace("Hello....");
}
The above function takes zero parameters and returns nothing. It just prints "Hello...";
If we want to declare global function we need to use the _global identifier. For eg:
_global.sayHello() {
trace("hello");
}
Passing parameters to methods Parameters are used for passing some values to the function so that the function can operate on that values. To pass a parameter to a function include the necessary parameters in the function definition separated by commas. For eg:
function sayHello(name) {
trace("Hello "+ name);
}
or function say(greeting, name) {
trace(greeting + name);
}
Returning a value from function A function can return a value to the calling function using the return keyword. For eg:
function sayHello(name) {
return "Hello .."+name;
}
the above function returns a string contain "Hello.." and the name we passed to the function.
Function Invocation To invoke or call a function just use the function name along with required parameters. For eg:
var greetings = sayHello("CGShelf");
The above statement calls the function sayHello with one parameter and stores the returned value to variable greetings.