What the Function!?

Functions (aka methods) are the bread and butter of any application. Without them you can’t do much of anything. So I thought I would show you how to write one.

The basic syntax of a function is below:

public function myFunction():void{
trace("Function was called");
//calling the function
myFunction(); //will trace out Function was called

The first item is the access modifier (for more details on access modifiers go here). If you’re writing functions on the timeline of an FLA. Defining an access modifier for your function will fire an error so just leave that part off.

The next item is the keyword function.

The next item is the name of the function followed by curved braces. You can call the function anything you would like. Convention dictates that the first letter of the first word is lowercase and after that uppercase – myReallyCoolNewFuctionName.

Next is the colon and the word void. This is the return type for your function. If your function was going to return a value you need to tell Flash what the data type is. For example, if I wrote a function that returned a string variable. The return type would be String

private function myReturnDataFunction():String{
return stringVariableName;
//calling the function
var data:String = myReturnDataFunction();
That is the basic syntax for creating a function.

Passing Arguments

Sometimes you will need to pass data to a function. Luckily that is pretty simple:

private function myFunction(name:String):void{
//calling the function
myFunction("Ryan"); //will trace out Ryan

In example above, the function is expecting an argument that is a String. We use name as a placeholder of sorts so can have a reference to the string that is passed to the function. You can have as many arguments as you need just separate then with a comma

private function myFunction(arg1:Type,arg2:Type):void{

Leave a Reply