Flash / Flex / ActionScript/Class/Constructor

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

A class named Product with a constructor and a method

 
public class Product {
  var price:Number;
  public function Product (  ) {
  }
  public function doSomething (  ):void {
  }
}



Add assignment code to class constructor

 
package com.wbex {
  internal class MyClass {
    internal var varName = "Unnamed";
    public function MyClass (name) {
      this.varName = name;
    }
  }
}



Add public attribute to contrustor.

 
class SomeClass {
  public function SomeClass (  ) {
  }
}
The following code adds a constructor method to MyClass.
package com.wbex {
  public class MyClass {
    public function MyClass (  ) {
    }
  }
}



Constructor with parameter

 
package{
  import flash.display.Sprite;
  
  public class Main extends Sprite{
    public function Main(){
        
        var m:MultiplyNumbers = new MultiplyNumbers(2,3);
    }
  }
}
     class MultiplyNumbers {
          
          public function MultiplyNumbers(num1:Number,num2:Number):void {
               trace(num1*num2);
          }
          
     }



Creating a Constructor

 
/*
function ClassName([parameterList]) { 
  // Constructor code goes here. 
}
*/
class Car {
  private var _sMake:String = null;
  private var _sModel:String = null;
  private var _sExteriorColor:String = null;
  public function Car() {
    switch(arguments.length) {
      case 3:
        _sExteriorColor = arguments[2];
      case 2:
        _sModel = arguments[1];
      case 1:
        _sMake = arguments[0];
    }
  }
}



Declare a constructor method for the Example class

 
package{
  import flash.display.Sprite;
  
  public class Main extends Sprite{
    public function Main(){
        var example:Example = new Example(  );
        trace(example.getId(  )); // Displays: Example Class
    }
  }
}
class Example {
        private var _id:String;
        public function Example(  ) {
            _id = "Example Class";
        }
        public function getId(  ):String {
            return _id;
        }
    }



Set the memeber variable in constructor

 
package{
  import flash.display.Sprite;
  
  public class Main extends Sprite{
    public function Main(){
      var crTest:Car = new Car("A", "B", "C");

    }
  }
}
     class Car {
     
       private var _sMake:String = null;
       private var _sModel:String = null;
       private var _sExteriorColor:String = null;
       private var _nMileage:Number;
     
     
       public function Car(sMake:String,
                           sModel:String,
                            sExteriorColor:String)
      {
         _sMake = sMake;
         _sModel = sModel;
         _sExteriorColor = sExteriorColor;
     
         _nMileage = 0;
       }
     
}