User Guide
98 ActionScript Language and Syntax
In ActionScript 3.0, all arguments are passed by reference because all values are stored as
objects. However, objects that belong to the primitive data types, which includes Boolean,
Number, int, uint, and String, have special operators that make them behave as if they were
passed by value. For example, the following code creates a function named
passPrimitives() that defines two parameters named xParam and yParam, both of type int.
These parameters are similar to local variables declared inside the body of the
passPrimitives() function. When the function is called with the arguments xValue and
yValue, the parameters xParam and yParam are initialized with references to the int objects
represented by
xValue and yValue. Because the arguments are primitives, they behave as if
passed by value. Although
xParam and yParam initially contain only references to the xValue
and
yValue objects, any changes to the variables within the function body generate new
copies of the values in memory.
function passPrimitives(xParam:int, yParam:int):void
{
xParam++;
yParam++;
trace(xParam, yParam);
}
var xValue:int = 10;
var yValue:int = 15;
trace(xValue, yValue); // 10 15
passPrimitives(xValue, yValue); // 11 16
trace(xValue, yValue); // 10 15
Within the passPrimitives() function, the values of xParam and yParam are incremented,
but this does not affect the values of
xValue and yValue, as shown in the last trace
statement. This would be true even if the parameters were named identically to the variables,
xValue and yValue, because the xValue and yValue inside the function would point to new
locations in memory that exist separately from the variables of the same name outside the
function.
All other objects—that is, objects that do not belong to the primitive data types—are always
passed by reference, which gives you ability to change the value of the original variable. For
example, the following code creates an object named
objVar with two properties, x and y.
The object is passed as an argument to the
passByRef() function. Because the object is not a
primitive type, the object is not only passed by reference, but also stays a reference. This
means that changes made to the parameters within the function will affect the object
properties outside the function.
function passByRef(objParam:Object):void
{
objParam.x++;
objParam.y++;