开发者

Can I var scope a function? Prevent it from appearing in the global variables scope

I'm cleaning up a large website's huge variables scope, normally when cleaning up these things I find the variables and var scope them.

Problem is; say I have a function declaration in a view(cfscript):

function myFunction(){
    //doStuff
}

myFunction is now available in the variables scope, 开发者_如何学JAVAit is however only used on this page so i want it in the local scope.

I've tried:

function local.myFunction(){
    //doStuff
}
//error!

var myFunction = "";
function myFunction(){
    //doStuff
}
//just creates a local string and a global function...

var function myFunction(){
    //doStuff
}
//no error but function is still not local...

the following however does work, it does feel kinda nasty though...

function myTMPFunction(){
    //doStuff
}
var myFunction = myTMPFunction;
structDelete(VARIABLES, "myTMPFunction");

is there no better, clean way?


is there no better, clean way?

Yes, there is. It is called ColdFusion components aka CFC.

I suspect that you mis-use local scope concept a bit, but you did not say whether your code is inside a CFC or not, so I can only guess: if you are refactoring CFC, what you want is incapsulation, otherwise you just want to start using components and then local scope inside the methods.


Based on your comment to Sergii's post,

its used recursive to generate HTML

I would say maybe you should refactor the function into a custom tag.

I generally avoid directly outputting anything from functions and use Custom Tags instead. When I use functions I return some value (or void).

Without more specific information on what the function does, though, it will be hard to give a more concrete answer than that.

However, while not the prettiest, I think your work-around solution would also work, if you'd rather not go through the effort to use a Custom Tag.

function myTMPFunction(){
    //doStuff
}
var myFunction = myTMPFunction;
structDelete(VARIABLES, "myTMPFunction");


The local scope is only really important within the context of a function. The reason that you var scope variables in a cfc is so that variables that should be local to a function don't leak out of the scope of the function into the component. This becomes especially important if you have components in a persistent scope like session or application.

component{

    public void function leakyVariable(){
            //this is in variables scope so a) it will exist longer 

            //than this function call and other functions can access it
        foo = "Foo"; 

        //do stuff
    }

    public void function grabLeakyVariable(){
            //look i have a foo
        var foobar = foo & "bar";
    }

}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜