views:

378

answers:

3

We have a very large JavaScript application where after many months of coding there have inevitably sprung a couple scope slip ups where a variable is defined in the following fashion:

function() {  
    x = 5; ...  
}

instead of:

function() {  
    var x = 5; ...  
}

This is happening somewhere -- We're not sure where -- and searching for the variable name in question is difficult since it's a common word that appears 1000s of times in our source.

Is there a way to ask Firebug to break on the line that first creates a given global variable? To clarify, I would like to break at exactly the instant when window['X'] switches from undefined to defined, and to break on the line that is executing at that instant.

I've tried creating a watch expression and hoped I could turn it into a breakpoint, but I can't seem to create watch expressions without some kind of context or scope.

If this isn't possible with Firebug, I'd be interested in anything that can accomplish this in Firefox in general.

+4  A: 

This little script would do the trick provided a few things:

  1. You know the name of the variable
  2. You don't have a variable with that name in the global scope (declared outside functions), but only inside functions.
  3. There are calls to the function that declares the variable.

    <script type="text/javascript">

    window.__defineSetter__("x", function(value) { console.trace(); });

    x = 1;

    </script>

You'll get a trace of the executed code before that assignment.

It may fail to report some situations, so take a look at jslint. Load all your JS files right there and lint them.

Ionuț G. Stan
Is there something wrong with the code formatter? I can't get it to work with my example.
Ionuț G. Stan
yeah you have to add a lot of spaces before each line to have it formatted -- had the same issue entering my question :)
Maciek
A: 

Thanks. Here's the solution I ended up using by modifying Ionut G. Stan's solution:

window.__defineSetter__("name", function(value) {
    if(value=="div"){
        debugger;
    }
});

I used debugger instead of console.trace() so I could stop and look at it mid-execution. With console.trace I got a bazillion trace statements due to this line executing 100s of times.

The leaky scope turned out to be buried in Dojo, where Dojo is setting that variable to the name of a processed element.

Maciek
I've used "debugger" initially, but I couldn't see the line where the variable was assigned, so I thought it won't help you. Anyway, I'm glad I could help.
Ionuț G. Stan
+1  A: 

View your web page on the SeaMonkey browser (I use version 1.1.16) and look at the error console, you will see a message of this type for each assignment to an undeclared variable :

Warning: assignment to undeclared variable x
Source File: http://....js
Line: ##
Hans B PUFAL