AS1 OOP: Object Scope
by senocular
The Arguments Object
In each function call there is created for it, in the local
scope of that call, an object called arguments. The
arguments itself is really just an array. It contains all of
the values that were passed in to the function when it was
called. For example, in the function call
- myFunction("A", 2);
myFunction receives 2 arguments, the letter "A" and the
number 2. In the body of that function, arguments would be
an array with arguments[0] containing "A" and arguments[1]
containing 2.
- myFunction = function(){
- trace(arguments[0]); // traces "A"
- trace(arguments[1]); // traces 2
- };
- myFunction("A", 2);
Aside from providing the arguments of the function call,
the arguments object also has 2 other properties, callee and
caller.
Arguments.callee represents the function object running
call. Arguments.caller is one up on callee representing any
function (if there is one) calling the callee. If a function
was not run from another function then there is no caller
and arguments.caller will be null. Arguments.callee will
always exist though, as to run a function, there obviously
needs to be a function. Arguments.callee represents the this
of the function object itself. Consider the following
example.
- tracePhrase = function(){
- trace(arguments.callee.phrase); // traces "Phrase
accessed through callee"
- };
- tracePhrase.phrase = "Phrase accessed through callee";
- tracePhrase();
The phrase property was added directly to the tracePhrase
function. Accessing its value means using arguments.callee
to get to the tracePhrase function object itself. Granted,
you could use tracePhrase directly, but what if you don’t
know the name of the function?
Callee is for the function calling the function.
- runTracePhrase = function(){
- tracePhrase();
- };
- tracePhrase = function(){
- trace(arguments.callee.phrase); // traces "Phrase
accessed through callee"
- trace(arguments.caller == runTracePhrase); // traces
true
- };
- tracePhrase.phrase = "Phrase accessed through callee";
- runTracePhrase();
Since runTracePhrase is the function that called
tracePhrase, arguments.caller in tracePhrase is a reference
to the runTracePhrase function. Though the arguments is a
powerful and helpful object on a whole, I can’t say
arguments.caller is used often so don’t worry if you forget
what it means.
And that’s about it for object basics. Now its time to
get into the creation of custom objects and custom classes.
For more on scope, see Timothée Groleau’s in depth
article
Scope Chain and Memory Waste in Flash MX.