Flash / Flex / ActionScript/Class/Method

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

Adding Static Methods to a Class

   <source lang="java">

/* 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");
  
  }

}

       </source>
   
  


A simple example of a method declaration using parameters

   <source lang="java">

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;
   }
 }

}

       </source>
   
  


Change member variable value in member method

   <source lang="java">

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();
         }
         
    }
       </source>
   
  


Create a method and then call it by name

   <source lang="java">

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);
       }
   }

}

       </source>
   
  


Defining Methods for a Class

   <source lang="java">

/* 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.");
     }
   }

}

       </source>