Class Variable

3 posts

Flag Post

Hi, I’m having trouble understanding AS3 Classes. I would like to store a class into a variable. For example:

Filename: Assets.as
Package: Assets
Class: Assets

Main.as can (import Assets.*;) and access (public static vars) by referencing them (Assets.Assets.somestaticvariable). All is good.

Main.as can also declare (private static var AA:Class=Assets.Assets;) in its class section and access the same variable above via (AA.somestaticvariable). All still good.

somestaticvariable can be any singleton (int, Number, Sprite, …). However, it cannot be an (Array, Vector, or function). WHY?

In main.as:
Assets.Assets.imgArr.push(…); works, all other .as files referencing this global array are in sync.
AA.imgArr.push(…); blows chunks.

Calling a static function:
Assets.Assets.somestaticfunction(…); works.
AA.somestaticfunction(…); wont even compile.

I’ve also tried to declare AA: (private static var AA:Class=ApplicationDomain.currentDomain.getDefinition(“Assets.Assets”) as Class;) with the appropriate import, and same results as other declaration.

Why are the singletons working, but the array and functions failing? all are declared (public static var).

Thank you.

 
Flag Post

I’m having difficulties reading this.

 
Flag Post

You cannot call a static function or variable from an instance of an object.

You must do this:


ClassName.StaticThing

NOT

var obj:ClassName = new ClassName();
obj.StaticThing

Making something static means that it doesn’t apply to an instance of this class, but to the class in general.

Think of it as a ‘Human’ class. You declare an instance called ‘var Bob:Human = new Human();’. A non-static variable or function would be specific to Bob, where a static variable or function would be not specific to Bob, but to all instances made from Human. So Bob has a non-static variable called skin colour since it is unique to that instance of human, but has a static function called Reflex since it common and has no differences between any instance of Human (assuming all Human’s have the same reflex with no differences).

I hope that made sense. Just remember that to call static members through the class name xD.