Actionscript 3: Can someone explain to me the concept of static variables and methods?

后端 未结 3 1887
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-15 09:08

I\'m learning AS3, and am a bit confused as to what a static variable or method does, or how it differs from a method or variable without this keyword. This should be simple

3条回答
  •  忘掉有多难
    2020-12-15 09:34

    static specifies that a variable, constant or method belongs to the class instead of the instances of the class. static variable, function or constant can be accessed without creating an instance of the class i.e SomeClass.staticVar. They are not inherited by any subclass and only classes (no interfaces) can have static members.
    A static function can not access any non-static members (variables, constants or functions) of the class and you can not use this or super inside a static function. Here is a simple example.

    public class SomeClass 
    {
      private var s:String;
      public static constant i:Number;
      public static var j:Number = 10;
    
      public static function getJ():Number 
      {
        return SomeClass.j;
      }
      public static function getSomeString():String 
      {
        return "someString";
      }
    }
    

    In the TestStatic, static variables and functions can be accessed without creating an instance of SomeClass.

    public class TestStaic 
    {
      public function TestStaic():void 
      {
        trace(SomeClass.j);  // prints 10
        trace(SomeClass.getSomeString());  //prints "someString"
        SomeClass.j++; 
        trace(SomeClass.j);  //prints 11
      }
    }
    

提交回复
热议问题