Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Have Firebug break when a global variable x is defined

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 without using the var keyword 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 a defined value, and to break statement.

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.

like image 701
Maciek Avatar asked Jun 18 '09 15:06

Maciek


1 Answers

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.

this little script would do the trick:

<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.

like image 181
Ionuț G. Stan Avatar answered Oct 30 '22 23:10

Ionuț G. Stan