This code, which is one way to create a simple object, creates a new object instance and
defines a few properties within the object.
3.
Now enter the following ActionScript after the code you entered in step 2.
// The second way
var secondObj:Object = {firstVar:"hello world", secondVar:28,
thirdVar:new Date(1980, 0, 1)};
This is another way of creating an object. Both objects are equivalent. This code above
creates a new object and initializes some properties using the object shorthand notation.
4.
To loop over each of the previous objects and display the contents of objects, add the
following ActionScript on Frame 1 of the Timeline (after the code you've already entered):
var i:String;
for (i in firstObj) {
trace(i + ": " + firstObj[i]);
}
5.
Select Control > Test Movie, and the following text appears in the Output panel:
firstVar: hello world
secondVar: 28
thirdVar: Tue Jan 1 00:00:00 GMT-0800 1980
You can also use arrays to create objects. Instead of having a series of variables such as
,
firstname1
firstname2
make an array of objects to represent the same data. This technique is demonstrated next.
To use an array to create an object:
1.
Create a new Flash document, and save it as arrayObject.fla.
2.
Select Frame 1 of the Timeline, and type the following ActionScript into the Actions panel:
var usersArr:Array = new Array();
usersArr.push({firstname:"George"});
usersArr.push({firstname:"John"});
usersArr.push({firstname:"Thomas"});
The benefit of organizing variables into arrays and objects is that it becomes much easier
to loop over the variables and see the values, as shown in the following step.
3.
Type the following code after the ActionScript you added in step 2.
var i:Number;
for (i = 0; i < usersArr.length; i++) {
trace(usersArr[i].firstname); // George, John, Thomas
}
4.
Select Control > Test Movie, and the following text appears in the Output panel:
George
John
Thomas
, and
to represent a collection of variables, you can
firstname3
Organizing data in objects
109
Need help?
Do you have a question about the FLASH 8-LEARNING ACTIONSCRIPT 2.0 IN FLASH and is the answer not in the manual?