Flash / Flex / ActionScript/Class/Method

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

Adding Static Methods to a Class

 
/*
static publicPrivateModifier function methodName([paramList]):datatype {
  // Method code goes here.
}
*/

package{
  import flash.display.Sprite;
  
  public class Main extends Sprite{
    public function Main(){
       Car.statcF();
    }
  }
}
class Car{
   static public function statcF(){
      trace("static");
   
   }
}



A simple example of a method declaration using parameters

 
package{
  import flash.display.Sprite;
  
  public class Main extends Sprite{
    public function Main(){
        var averageValue:Number = average(5, 11);
    }
    private function average(a:Number, b:Number):Number {
        return (a + b)/2;
    }
  }
}



Change member variable value in member method

 
class Car {
          
          public var speed:Number;
          public var direction:String;
          
          public var onSpeedChange:Function;
          public var onDirectionChange:Function;
          public function Car(speed,direction) {
               this.speed = speed;
               this.direction = direction;
          }
          public function increaseSpeed() {
               this.speed += 10;
               this.onSpeedChange();
          }
          public function setDirection(direction) {
               this.direction = direction;
               this.onDirectionChange();
          }
          
     }



Create a method and then call it by name

 
package {
    import flash.display.Sprite;
    public class Main extends Sprite
    {
        public function Main(  ) {
            for(var i:int=0;i<10;i++) {
                drawLine(  );
            }
        }
    
        private function drawLine(  ):void {
            graphics.lineStyle(1, Math.random(  ) * 0xffffff, 1);
            graphics.moveTo(Math.random(  ) * 400, Math.random(  ) * 400);
            graphics.lineTo(Math.random(  ) * 400, Math.random(  ) * 400);
        }
    }
}



Defining Methods for a Class

 
/*
The syntax for a public method is: 
public function methodName([parameterList]):datatype {
  // Method code goes here.
}
The syntax for a private method is almost identical: 
private function methodName([parameterList]):datatype {
  // Method code goes here.
}
*/
package{
  import flash.display.Sprite;
  
  public class Main extends Sprite{
    public function Main(){
        var crTest:Car = new Car();
        
        crTest.drive(true);  // Displays: Car is driving.
        crTest.drive(false);  // Displays: Car is stopped.
    }
  }
}
class Car {
    public function drive(bStart:Boolean):void {
      if(bStart) {
        trace("Car is driving.");
      }
      else {
        trace("Car is stopped.");
      }
    }
}