AS1 OOP: Object Basics
         by senocular  

Introduction
If you've been working with Actionscript for any decent amount of time, chances are you already know what your basic object is and what it allows and can do for you. An object is a construct saved to a variable in Actionscript which can contain other variable values inside of itself. These variable values, or properties , inside objects can take the form of values such as numbers and strings, or they can also be functions. They can even be other objects with variables of their own.

The code for making a standard generic object in Flash is as follows:

myObject = new Object();

The variable myObject then becomes a object variable which can then have more variables added to it using dot syntax like so.

myObject.name = "Fred";
myObject.num = 10;
myObject.isMyFirstObject = true;
myObject.traceHello = function(){
trace("Hello");
};

Dot syntax is also used to retrieve those values

trace(myObject.name); // traces "Fred";
trace(myObject.value); // traces 10;
trace(myObject.isMyFirstObject); // traces true;
myObject.traceHello(); // traces "Hello";

Like arrays, objects also have a shorthand method of declaration. Arrays, for example, can be declared one of two ways

myArray = new Array(1,2,3); // long
myArray = [1,2,3]; // short

Similarly, objects can be defined two different ways:

myObject = new Object(); // long
myObject = {}; // short

Using the shorthand version, like with arrays, you can make internal variable assignments inline. This way, you won't need to keep referencing the myObject variable to repeatedly add values to it

myObject = {name: "Fred", value: 10};

Here, myObject is an object declared with the name and properties already defined. Note that this method is for initial definition only. You cannot add values to an object in this manner. For that you would need to access the object variable directly for each new value as done previously.

The new Object(); command, however, does has a minor difference within its ability to define an object in comparison to the shorthand method. Using new Object() you can define what would be a default value for the object. Without this default value, or in using the shorthand syntax for object declaration, as myObject was declared above, the object technically has no real value of its own. The default value gives it one. For example, myObject can be given a base value of 5 by declaring it in the following manner.

myObject = new Object(5);
trace(myObject + 1); // traces 6

A you can see there, the object alone acts as the base value of what was given when it was defined.

 
 



SUPPORTERS:

kirupa.com's fast and reliable hosting provided by Media Temple.