Actionscript 3: Can someone explain to me the conc

2020-02-09 03:20发布

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 enough to answer, I think.

3条回答
倾城 Initia
2楼-- · 2020-02-09 04:01

A static variable or method is shared by all instances of a class. That's a pretty decent definition, but may not actually make it as clear as an example...

So in a class Foo maybe you'd want to have a static variable fooCounter to keep track of how many Foo's have been instantiated. (We'll just ignore thread safety for now).

public class Foo {
    private static var fooCounter:int = 0;

    public function Foo() {
        super();
        fooCounter++;
    }

    public static function howManyFoos():int {
        return fooCounter;
    }
}

So each time that you make a new Foo() in the above example, the counter gets incremented. So at any time if we want to know how many Foo's there are, we don't ask an instance for the value of the counter, we ask the Foo class since that information is "static" and applies to the entireFoo class.

var one:Foo = new Foo();
var two:Foo = new Foo();
trace("we have this many Foos: " + Foo.howManyFoos());  // should return 2
查看更多
ゆ 、 Hurt°
3楼-- · 2020-02-09 04:17

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
  }
}
查看更多
我命由我不由天
4楼-- · 2020-02-09 04:17

Another thing is static functions could only access static variables, and couldn't be override, see "hidden".

查看更多
登录 后发表回答