Flash / Flex / ActionScript/Function/function variable — различия между версиями

Материал из Web эксперт
Перейти к: навигация, поиск
м (1 версия)
 
(нет различий)

Текущая версия на 08:15, 26 мая 2010

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