Flash – AS3 : How to write function in AS3?

Please follow & like us :)

You can define any function using the generalized form below.

function functionName(argument):returnType{
statements; //implement your own logic
}

The first requirement for creating a function is to use the function keyword. You simply follow this by the name you want your function to have. You can almost use any name for this. We are going to use the name myFunction:

function myFunction(){
}

The code which the function will execute must be written between the curly brackets {}. We are going to make this function create a new MovieClip and set its .x and .yproperties:

function myFunction(){
var myMovie:MovieClip = new MovieClip();
myMovie.x=100;
myMovie.y=200;

}
The process for creating a function is called defining a function, in order to use a function you need to invoke it. Invoking the function is a separate process that requires
you to type the function name followed by two brackets:
function myFunction(){
var myMovie:MovieClip = new MovieClip();
myMovie.x=100;
myMovie.y=200;
} 

myFunction();

That last command will execute your function, you can simply type myFunction anytime you wish to create new MovieClip and set its x and y properties to 100 and 200 respectively. You must always remember to invoke your function because simply defining it will not execute any code.