Flash / Flex / ActionScript/Function/function variable
Содержание
A method assigned to a variable can be invoked via that variable using the standard parentheses operator, ( ).
package{
import flash.display.Sprite;
public class Main extends Sprite{
public function Main(){
var consume = eat;
consume();
}
public function eat () {
trace("eat");
}
}
}
Bound Methods, which is treated as a value
package{
import flash.display.Sprite;
public class Main extends Sprite{
public function Main(){
var consume = eat;
}
public function eat (calories) {
trace("eat");
}
}
}
Creating Anonymous Functions
//Here is the syntax for an anonymous function:
/*
function():datatype {
statements
};
*/
package{
import flash.display.Sprite;
public class Main extends Sprite{
public function Main(){
var fSayHi:Function = function(sName:String):void {
trace("Hi, " + sName);
};
fSayHi("Joey");
}
}
}
Function type variable
package{
import flash.display.Sprite;
public class Main extends Sprite{
public function Main(){
var fFactorial:Function = function(nOperand:Number):Number{
if(nOperand > 0){
return nOperand * arguments.callee(nOperand-1);
}
else{
return 1;
}
}
fFactorial(2);
}
}
}
Referencing Functions
package{
import flash.display.Sprite;
public class Main extends Sprite{
public function Main(){
var fArea:Function = calculateArea;
trace(fArea(6, 6));
}
function calculateArea(a:Number, b:Number):Number {
var nArea:Number = a * b;
return nArea;
}
}
}
// 36