www.webdeveloper.com
Results 1 to 3 of 3

Thread: Finding unintentional global variables

  1. #1
    Join Date
    Jan 2006
    Location
    Palmer Alaska
    Posts
    132

    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.
    I do not believe that javascript has a function like the python globals() and locals() functions,
    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.
    thanks
    tim

  2. #2
    Join Date
    Oct 2003
    Location
    Andover, UK
    Posts
    947
    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.

    Code:
    var myglobalvar = "hi, there!";
    alert(window.length);
    ...even though...

    Code:
    alert(window.myglobalvar);
    ...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.

  3. #3
    Join Date
    Jan 2006
    Location
    Palmer Alaska
    Posts
    132
    Your point 3) is well taken. I have written a script to programmatically parse a
    legacy "non-namespaced" javascript file into a list of variables, then create an output
    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.
    thanks
    tim

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles