Coldfusion Local scope outside of function?

What is local scope 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>

      

enter image description here

Change madVar2 assignment by adding keyword var

like:

function madness() {
    var madVar = "madness variable";
    var madVar2 = "madness two variable";

      

Output this output:

Image 2

+3


source to share


1 answer


Scope is Local

defined only within functions and should not be used outside of it.

Variables defined outside of functions are in scope by default variables

.

//that way
myVar = 0;
//will be the same as
variables.myVar = 0;

      

When you refer to a variable local.madVar2

that has been initialized outside of a function, you are mostly referring to local.madVar2

in scope variables

, that is, the variable madVar2

is stored inside a named structure Local

that is stored in scope variables

.

So, when scoped correctly, your code is treated like:



writeOutput("variables.local.madVar2: <BR>");     
writeDump(variables.local.madVar2);

      

Try resetting the scope variables

immediately after defining variables inside the function like:

var madVar = "madness variable";
madVar2 = "madness two variable";
writeDump(variables);
.....

      

You will see how the variables are scoped.

enter image description here

+7


source







All Articles