R – Properties undefined at their definition (1120 error)

actionscript-3flash

I've got a truly bizarre undefined error going here in my ActionScript (code simplified here):

package {
    public class Main extends Sprite {
        private function Test() {
            var testVar:Number = 10;
        }
    }
}

This returns an error: 1120: Access of undefined property testVar on line 4.

If I'm reading that correctly, it's complaining that the variable I'm trying to define hasn't yet been defined. Hence my confusion.

This all worked when the function Test was preceded by a giant object declaration, but now that I've moved that to a separate class, I'm getting this error for every single variable declaration in every method of the class.


Update:

It turns out the added class definitions at the end were causing the problem — but I've no idea why.

Adding

class A {}
class B {}

to the end of the .as file caused all the errors to occur, but including just class A {} or class B {} makes all the errors go away.

More confusing still, an even better solution was this:

class C {}
class A extends C {}
class B extends C {}

What is going on here?

Best Answer

So, I assume you are using CS4 for this, correct? There is a bug in the compiler for CS4 that doesn't allow you to do this... provided you are declaring anything as a local variable. You could make testVar a class instance variable and it would work.

If you want to add a single class outside of your package, then you can do this and still use local variables. However, adding a second will make the compiler choke.

BTW, this does work in CS3, but is generally considered a bad idea when using it for helper classes (classes that the main class inside the package will use.) The only time I use it is for declaring a class that is to be used as the argument for a singleton's constructor, for instance:

package {

    public class MySingletonClass extends Object {

        private static var _instance:MySingletonClass ;

        public function MySingletonClass ($singletonEnforcer:SingletonEnforcer) {}


        public static function getInstance(): MySingletonClass{
            if (MySingletonClass._instance == null) {
                MySingletonClass._instance = new MySingletonClass(new SingletonEnforcer());
            }
            return MySingletonClass._instance;
        }


        public static function get instance(): MySingletonClass{
            return MySingletonClass.getInstance();
        }
    }
}

class SingletonEnforcer extends Object {
    public function SingletonEnforcer() {}
}
Related Topic