Question

I have a vector in my Main class file that store objects. I will like to be able to add more objects to that SAME vector from a different class. I gave the vector in my main class the "public" modifier. I now need the syntax to reference it in my other class file

public var badChar:Vector.;

Was it helpful?

Solution

You have options. How you approach it is dependent on your project setup, and the needs of the property. Is it an instantiated object, or should there ever only be one (even if the class is instantiated multiple times)? Do you need direct access to it regardless of any relationship to the stage? Each solution below has pros and cons.


Class-to-Class via Stage

Assuming the following main foo.as class:

package {
    public class Foo {
        public var bool:Boolean = true;
    }
}

Bar class:

package {
    public class Bar extends Sprite {
        import flash.events.Event;

        public function Bar() {
            addEventListener(Event.ADDED_TO_STAGE, accessFoo);
        }

        private function accessFoo(e:Event):void {
            trace(this.parent["f"].bool); // traces "true"
        }
    }
}

Document Code:

var f:Foo = new Foo();
var b:Bar = new Bar();
addChild(b);

Inheritance

Foo Class:

package {
    public class Foo {
        public var bool:Boolean = true;
    }
}

Bar Class

package {
    public class Bar extends Foo {
        public function Bar() {
            trace(bool); // traces "true"
        }
    }
}

Class-to-Class via Static

Some disclaimers should be in order for Static properties, but I'll leave you to read up on those.

Foo Class:

package {
    public class Foo {
        public static var bool:Boolean = true;
    }
}

Bar Class

package {
    public class Bar {
        public function Bar() {
            trace(Foo.bool); // traces "true"
        }
    }
}

Direct Access via New Declaration

Foo Class:

package {
    public class Foo {
        public var bool:Boolean = true;
    }
}

Bar Class

package {
    public class Bar {
        import Foo;

        public function Bar() {
            trace(new Foo().bool); // traces "true"
        }
    }
}

Access via Sharing

Foo Class:

package {
    public class Foo {
        public var bool:Boolean = true;
    }
}

Bar Class

package {
    public class Bar {
        import Foo;
        public var fluffy:Foo;

        public function Bar() {
            trace(fluffy.bool);
        }
    }
}

Document Code:

var f:Foo = new Foo();
var b:Bar = new Bar();
b.fluffy = f;

Note that after the third line in the document code, fluffy is no longer an undeclared variable and will now point to the f object, where the properties updated in it (such as bool) will reflect inside of Bar.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top