Reputation: 1356
If my main class I define
var arrItems:Array=[];
and in a utility class (in a different file) I define
public class Util
{
public function Util()
{
var choices:Array[] = {
"1 item1 ",
"2 item2 ",
"3 item3 " };
How do in my main class access the elements of Util.choices and also assign them to arrItems?
In Java I would do
arrItems[i] = Util.choices[i];
Upvotes: 0
Views: 877
Reputation: 14905
It depends on how you're going to use choices. Is choices array constant or will it change over time? First lets assume it is constant that you can make it static property of Util class.
public class Util{
public static const choices:Array=["item1", "item2"];
}
Now yon can access choices like this:arrItems[i]=Util.choices[i];
public class Util{
private var _choices:Array;
public function Util():void{
choices=["item1", "item2"];
}
public function get choices():Array {
return _choices;
}
}
And in your main code you can access choices by instantiating Util class.var u:Util=new Util();
arrItems[i]=u.choices[i];
Upvotes: 0
Reputation: 9572
Same in AS3 , except that you should declare choices as a static var like so
public class Util
{
public static var choices:Array = {'item1' , 'item2' , 'item3'};
}
Upvotes: 1
Reputation: 740
This is a scope issue. You have declared the array choices inside the constructor of your Util class, and therefore it can only be referenced by name from inside this function. The first thing you will need to do is move it to the class level, like this.
public class Util{
//Also note you use [] for arrays, and {} for objects.
public var choices:Array = ["item 1", "item 2", "item 3"];
}
So, now that choices lives at the class level we can reference it by creating an instance of that class, like so...
//Inside another class somewhere...
var util:Util = new Util();
trace(util.choices[0]); // Outputs "item 1"
However, given your example it seems you only need one instance of this array for your entire program. An easy way to do this is by using the static modifier, which attaches the variable to the actual class (as opposed to an instance of the class) and you end up with something like this...
public class Util{
public static var choices:Array = ["item 1", "item 2", "item 3"];
}
//Anywhere else in your program
trace(Util.choices[0]); // Outputs "item 1"
Upvotes: 1
Reputation: 10530
I think you are tripping yourself up coming from Java. Take a look at an AS3 guide on Arrays to start. Such as Introduction to Arrays in ActionScript 3.0 - republicofcode.com. Hopefully this will give you a better understanding.
You might also want to look into Static vars.
Upvotes: 0