Finding unintentional global variables
FYI: I am more accustomed to python where a variable that is initialized within a function
has scope local to that function.
but it would be great if it did.
Aside from that, might someone know if any utilities that might produce a list of global
variables? Or pointers to discussion regarding best practices.
IOWS: I'm looking for a way to trouble-shoot and look for variables that were not defined in
a function with the 'var' keyword.
I don't think there's a simple way to do this, but a couple of points:
1) global vars are stored within the scope of the window object. However, since window is somewhat 'special' in comparison to other objects, it doesn't behave the same. Thus, the following returns 0, not 1.
var myglobalvar = "hi, there!";
...will find the variable you created.
2) You could theoretically do what you're asking by recursively traversing a script and discsounting any vars found that are properties of objects (i.e. local variables, since in JS functions and objects are effectively the same thing). You can read a function's properties via arguments.callee.
3) A good script these days operates within a namespace, where all data is a sub element of that namespace so there shouldn't be any global variables. If a var needs to be read by another function it can either be passed to it or, better, hardwired into one of the functions via funcname.varname = value, so it can be accessed from anywhere.
Not sure if this helps, but hey.
Your point 3) is well taken. I have written a script to programmatically parse a
document with writeln statements in try/catch constructs. Does a pretty good
of catching the "stray variables".
I must play with your window object approach a bit. That could also be edifying.
Users Browsing this Thread
There are currently 1 users browsing this thread. (0 members and 1 guests)