Flash / Flex / ActionScript/Class/static
Содержание
Reference static variable
class Bicycle
{
static public var wheels:Number = 2;
private var _gears:Number;
public function get gears():Number
{
return _gears;
}
public function Bicycle(numberOfGears:Number)
{
this._gears = numberOfGears;
for (var i:int = 0; i < Bicycle.wheels; i++)
{
//Prepare a wheel.
}
}
}
Static Constants
package{
import flash.display.Sprite;
public class Main extends Sprite{
public function Main(){
var stuntBike:Bicycle = new Bicycle();
stuntBike.performTrick("wheely"); //nothing happens
}
}
}
class Bicycle
{
static public const WHEELS:Number = 2;
//the rest of the class...
public function performTrick(trickName:String):void
{
switch (trickName)
{
case "wheelie":
//code goes here to wheelie
break;
case "bunnyhop":
//code goes here to bunny hop
break;
case "stoppie":
//code goes here to stoppie
break;
}
}
}
Static Methods
package{
import flash.display.Sprite;
public class Main extends Sprite{
public function Main(){
StringUtils.contains("me@moock.org", "@");
}
}
}
internal class StringUtils {
public static function contains (string, character) {
for (var i:int = 0; i <= string.length; i++) {
if (string.charAt(i) == character) {
return true;
}
}
return false;
}
}
Static Variables
/*
class SomeClass {
static var identifier = value;
}
class SomeClass {
private static var identifier = value;
}
SomeClass.identifier = value;
*/
package{
import flash.display.Sprite;
public class Main extends Sprite{
public function Main(){
trace(MyClass.maxNameLength);
}
}
}
internal class MyClass {
static var maxNameLength = 20;
static var maxCalories = 2000;
}
Static Variables: define methods and properties that belong to the class itself, rather than their instances.
package{
import flash.display.Sprite;
public class Main extends Sprite{
public function Main(){
var fixedGear:Bicycle = new Bicycle(1);
// trace(fixedGear.wheels); //Wrong! Compiler error.
trace(Bicycle.wheels); //Right! 2
}
}
}
class Bicycle
{
public static var wheels:Number = 2;
private var _gears:Number;
public function get gears():Number
{
return _gears;
}
public function Bicycle(numberOfGears:Number)
{
this._gears = numberOfGears;
}
}
Using Static Methods and Properties
package{
import flash.display.Sprite;
public class Main extends Sprite{
public function Main(){
var eighteenSpeed:Bicycle = new Bicycle(18);
var fixedGear:Bicycle = new Bicycle(1);
trace(eighteenSpeed.gears); //18
trace(fixedGear.gears); //1
}
}
}
class Bicycle
{
private var _gears:Number;
public function get gears():Number
{
return _gears;
}
public function Bicycle(numberOfGears:Number)
{
this._gears = numberOfGears;
}
}