Chapter iii(advance function)

5
Functions - Advanced Use

Transcript of Chapter iii(advance function)

Page 1: Chapter iii(advance function)

Functions - Advanced Use

Page 2: Chapter iii(advance function)

Setting parameters with default value• 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 .

• function sayHy(name:String = 'You') { trace('Nice to meet '+ name);

}sayHy('Marius'); // displays: Nice to meet MariussayHy(); // displays: Nice to meet You

Page 3: Chapter iii(advance function)

Using 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). • // define a function with "rest parameters"

function testF2(... nums):void{var latura:Number = 0;for each (var num:Number in nums){ latura += num; // add the current value to "latura }testClip.width = latura; testClip.height = latura;}testF2(8, 20, 40, 50); // calls the functions with multiple arguments

Page 4: Chapter iii(advance function)

Assign function to a variable• 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.

// define a function with 3 parameters in a variablevar 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" parametervrF(testClip, 2.5, 1.4);

Page 5: Chapter iii(advance function)

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)

• // define a recursive functionfunction 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