Actionscript Course

In this lesson there are presented more advanced things about using functions.
The exemples in this tutorial use an Instance of a Movie Clip symbol created on the Stage (in Flash).
So, before to start testing the exemples below, open a new Flash document, select "Rectangle tool" and draw a rectangle on the Stage, then convert it in Movie Clip symbol (from Modify -> Convert to Symbol, and for Type select "Movie Clip").
Make sure the object is selected, open the "Properties panel" and add a name for this instance, testClip, like in the picture below.
testClip instance

Setting parameters with default value

In ActionScript 3.0, you can set default values for a function's parameters. To do this, simply add an equal sign (=) and the default value after an parameter name, as follows.
function sayHy(name:String = 'You') {
  trace('Nice to meet '+ name);
}

sayHy('Marius');        // displays:  Nice to meet Marius
sayHy();        // displays:  Nice to meet You
- As you can see, the parameter with a default value becomes optional, you can call the function without adding an argument for that parameters. If you not pass an argument, the function will use it with the default value.

All parameters that have a default value must be placed last in the order of arguments.
              function setAccount(name:String, pass:String, email:String = null)


Let's test another example, using the "testClip" instance (the rectangle created at the beginning of this lesson).
In the same document in which you have created the rectangle, right-click on Frame 1 in the Timeline, and choose Actions. Then, in the "Actions panel" add the following code:
// define a function with 2 parameters, the second is default
function testF(dy:Number, rotatie:int = 45):void
{
  // sets "y" and "rotation" properties for "testClip" instance
  testClip.y = dy;
  testClip.rotation = rotatie;
}

// call the function, passing only the required argument (dy)
testF(10);
- "testClip.y" sets the Y distance, "rotation" is a property used to rotate the object.
Press "Ctrl+Enter" to see the effect of this script. The Flash player will position and rotate the rectangle, like in the image below.
testClip instance 2
To download the FLA file with this example, click testClip Example.

Using the rest parameter (...)

ActionScript 3.0 adds a new feature called the rest parameter.
The "rest parameter" is a symbol (...) that represents a variable number of arguments as an array followed by a name for that array (... array_name). "array_name" will be used for the array containing the values.
The rest parameter allows you to call a function with as many arguments as you like; their values will be stored in the "array_name" Array.

Here is an example (it uses the same document in which you have created the "testClip" instance).
- Right-click on Frame 1, and choose Actions. Then, in the "Actions panel" delete any existing code and add the following code:
// define a function with "rest parameters"
function testF2(... nums):void
{
  // declare a variable which will be used to store the sum of the values passed in arguments
  var latura:Number = 0;

  // define a "for each..in" to access each value stored in "nums" Array
  for each (var num:Number in nums)
  {
    latura += num;        // add the current value to "latura
  }

  // uses the variable, "latura" to set the 'width' and 'height' for "testClip"
  testClip.width = latura;
  testClip.height = latura;
}

testF2(8, 20, 40, 50);          // calls the functions with multiple arguments
- All values passed to the "testF2()" function are stored in the "nums" Array.
- The "width" and "height" properties sets the width and the height of the object (in this case with a value of 118, 8+20+40+50 = 118).
Press "Ctrl+Enter" to see the result. The rectangle on the stage becomes a square, like in the picture below.
testClip instance 3
To download the FLA file with this example, click testClip Example 2.

The rest parameter can also be used with other required parameters. The required parameters will have their own names and will exist independent of the rest array. Any additional arguments passed after the required ones will be stored in the rest array.
              function test(param1, ... rest_array)

Assign function to a variable

Another way to define a function is to assign it to a variable of type Function.
The syntax is:
var someVariabe:Function = function (param1, param2, ...) {
  // code to execute
}
- Once assigned, the function can then be invoked through that variable, as in:
someVariabe(arg1, arg2, ...)
Because the function is assigned to a variable, it resides in memory as any normal variable. So, the value of this variable can be changed or deleted.

Example:
- Add the following code in the Flash document in which you have created the instance "testClip" (delete any other ActionScript code in Actions panel), then press "Ctrl+Enter".
// define a function with 3 parameters in a variable
var vrF:Function = function (obj:MovieClip, sx:Number, sy:Number):*
    {
      // "obj" must be the instance of a MivieClip
      // define "scaleX" and "scaleY" properties for "obj
      obj.scaleX = sx;
      obj.scaleY = sy;
    }

// call the function, passing the 'testClip' instance for the "obj" parameter
vrF(testClip, 2.5, 1.4);
- the variable name (vrF) its the name used to call the function.
- "scaleX" and "scaleY" multiply the width and height of the object.

Variables and Functions

The variables declared outside a function (before the function definition) can be used in the function code.
The variables created within a function can only be used inside the code of that function. These variables are called "local variables", and they not exists outside the function.

Example (see the comments in code):
var ext_vr:int = 18;        // variable created outside any function

// define a function which use the "ext_vr" variable
function oFunctie():Number
{
  // create a local variable
  var in_vr:Number = 7;

  // add the value of the external variable "ext_vr" to the local variable
  in_vr += ext_vr;

  return in_vr;        // return the values of "in_vr"
}

trace(oFunctie());      // displays in Output the value returned by the function (25)

// Try to access the local variable "in_vr" outside the function (delete "//")
// trace(in_vr);
- Notice that the oFunctie() can use the value of the external variable "ext_vr". But if you try to access the local variable "in_vr" outside the function (deleting the "//" before trace(in_vr);), you'll get an error message.

Recursive Functions

A recursive function is a function that calls itself.
To avoid infinite recursion (when a function never stops calling itself), use an "if()" condition to control when a recursive function calls itself.
One classic use of the recursive functions is to calculate the mathematical factorial of a number, which is the product of all positive integers less than or equal to the number (1*2*3*4*...*n).
In the next example it is created a recursive function to calculate the mathematical factorial of a number passed in argument.
// define a recursive function
function factorial(n:uint):uint
{
  // if n>0, multiply 'n' auto-calling function
  if(n > 0)
  {
    return (n * factorial(n-1));
  }
  else { return 1; }       // return 1 when n>0 is false
}

// store in a variable the value returned by factorial(8)
var fact:uint = factorial(8);

trace(fact);          // Output:  40320

Daily Test with Code Example

HTML
CSS
JavaScript
PHP-MySQL
Which tag create a highlighted bolded text?
<q> <strong> <em>
<p>Address: <strong>http://CoursesWeb.net/</strong> - Tutorials.</p>
Which of these CSS codes displays the text bolded?
text-size: 18px; font-style: italic; font-weight: 800;
#id {
  font-weight: 800;
}
What JavaScript function can be used to call another function multiple times, to a specified time interval?
setInterval() setTimeout() push()
function someFunction() { alert("CoursesWeb.net"); }
setInterval("someFunction()", 2000);
Click on the correctly defined variable in PHP.
var vname = 8; $vname = 8; $vname == 8;
$vname = 8;
echo $vname;
Functions - Advanced Use

Last accessed pages

  1. Laravel - Validation (806)
  2. SHA1 Encrypt data in JavaScript (35329)
  3. Creating Gradients (950)
  4. PHP OOP - Final Classes and Methods (5407)
  5. Check and Validate input field when loses focus, with PHP via Ajax (6762)

Popular pages this month

  1. Courses Web: PHP-MySQL JavaScript Node.js Ajax HTML CSS (299)
  2. Read Excel file data in PHP - PhpExcelReader (101)
  3. The Four Agreements (90)
  4. PHP Unzipper - Extract Zip, Rar Archives (87)
  5. The Mastery of Love (83)