AS1 OOP: Object Scope
by senocular
Local Scope
We’ll start backwards with the local scope. Local scope
refers the the current base scope of any written code. For
any code written directly in a timeline, the local scope is
the scope of that timeline. Since most of your code is
written directly on your timelines, this probably applies to
much of your script – at least that which is not within the
definition of functions.
A code block for a function can access _global and
current timeline variables directly simply by using their
name. Functions have access to those scopes in that manner
(and everything does for _global values). For instance, if
you define a variable and a function in the same timeline,
the function, as long as its called after the definition of
the variable, will be able to access the value of that
variable within its function call.
- timelineValue = "timeline variable";
- accessTimelineVariable = function(){
- trace(timelineValue); // traces "timeline variable"
- };
- accessTimelineVariable();
Each function call itself, however, also has its own
local scope. This is a scope specific to each call as if the
call itself was an object. Variables within this scope are
accessed just as timeline variables are only variables local
to the function call are not accessible in the timeline
outside of that function. You can define variables in this
scope using the var keyword. If var is not used in a
function call in defining variables, the variables will be
defined in the timeline itself and will actually be
accessible outside of that function.
- defineVariables = function(){
- var local = "local value";
- timeline = "timeline value";
- trace(local); // traces "local value"
- trace(timeline); // traces "timeline value"
- };
- defineVariables();
- trace(local); // traces undefined
- trace(timeline); // traces "timeline value"
When parameters are passed into a function call, those
values are assigned as arguments that exist in the local
scope of that call.
- traceArguments = function(argA, argB){
- trace(argA); // traces 1
- trace(argB); // traces 2
- };
- traceArguments(1, 2);
Its this local scope that you would want to define
variables that are specific to each function call, such as
function arguments, that are to be used only in that code
that are not to interfere with anything else. Be sure to
remember var or those variables will be set in the timeline
and could potentially disrupt your script and other actions
or values within your timeline.