What exactly is the local scope defined outside of a function?
Consider the following code:
<cfscript>
local.madVar2 = "Local scope variable";
function madness() {
var madVar = "madness variable";
madVar2 = "madness two variable";
writeOutput("local: <BR>");
writeDump(local);
writeOutput("========================================= <BR>");
writeOutput("local.madVar2: <BR>");
writeDump(local.madVar2);
writeOutput("<BR>========================================= <BR>");
writeOutput("madVar2: <BR>");
writeDump(madVar2);
writeOutput("<BR>========================================= <BR>");
writeOutput("variables.madVar2: <BR>");
writeDump(variables.madVar2);
writeOutput("<BR>========================================= <BR>");
}
</cfscript>
Changing the madVar2 assignment by adding the var
keyword, like this:
function madness() {
var madVar = "madness variable";
var madVar2 = "madness two variable";
Will yield this output:
The
Local
scope is only defined within functions and should not be used outside of it.Variables defined outside the functions, default to the
variables
scope.When you refer to
local.madVar2
variable, which was initialized outside the function you're essentially referring to thelocal.madVar2
in thevariables
scope i.e the variablemadVar2
is stored inside a struct namedlocal
which is stored in thevariables
scope.So essentially, with the proper scoping in place your code is treated as:
Try dumping the
variables
scope just after defining the variables inside the function as:You will see how the variables fall into scopes.