Hi, 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.
views:
1034answers:
2The last line doesn't print 11, only sets j to 11 :P
Seth Illgard
2009-11-15 18:57:58
thanks :) edited the same.
bhups
2009-11-15 18:59:59
A good scenario where you would use a static variable/function is if you are generating a unique id for an instance of a class. Since the variable belongs to the class you can call a static method (that would increment the counter) and then assign it to the instance of the class (most likely in the constructor). Thats how I first learnt about them :)
Allan
2009-11-15 22:54:28
And very common use of static keyword is in 'Singleton Design Pattern'. http://en.wikipedia.org/wiki/Singleton_pattern
bhups
2009-11-16 05:21:43
+3
A:
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
dustmachine
2009-11-15 19:12:44