0

I want to determine when a particular variable is changed. I have had great success using this code to watch any property of any object that I can access, but can it be used for a variable declared like this?:

$(                  // line 1
  function(){       // line 2
    var A;          // line 3
    // ... lots of code that uses A as if it were a global. I wanna see what part of this code sets A ...
  }                 // line 5999
);                  // line 6000

Surely A does not end up as a property of window. Is it perhaps a property of the anonymous function object which spans lines 2 thru 5999? So if I name the function so I can reference it am I able to use watch on the A var/prop somehow?

What other methods are available to me to figure out where the var gets set?

Steven Lu
  • 41,389
  • 58
  • 210
  • 364
  • It's not a property of anything *(at least not anything to which your code has access)*. – I Hate Lazy Nov 21 '12 at 16:32
  • It appears so. According to http://docstore.mik.ua/orelly/webprog/jscript/ch04_06.htm I need a ref to the "call object". How can I obtain it? – Steven Lu Nov 21 '12 at 16:34
  • You can't. It an internal object used in the execution context of the function. It's not available to your code. – I Hate Lazy Nov 21 '12 at 16:36

2 Answers2

1

This might seem bit insane but, with a little modification, you'll be able to watch the variables pointer.

(function() {
    window.ox = x = {};

    x.y = 5;
})();

alert(ox.y);

This pulls it into the global territory, and should allow you to observe variable x from the global variable ox. ​

roacher
  • 666
  • 3
  • 8
  • So I tried to apply this but couldn't get it working. `Window.ox` if watched will not respond when x is re-assigned. – Steven Lu Dec 13 '12 at 00:58
0

You can't use Object.prototype.watch on that variable, simply because it's a variable, not an object property. Regardless of its scope (which is the anonymous function you mentioned).

If you're trying to do that for debugging purposes, I believe you can watch it from your browser's developer tools.

bfavaretto
  • 71,580
  • 16
  • 111
  • 150
  • When I try to use the webkit watch expressions it is not in the right scope (it's no more powerful than a macro for typing the stuff into the console) – Steven Lu Nov 21 '12 at 16:41
  • Try Firefox+Firebug. From the Script tab, you can watch any variable on your source code. I'm not sure how to to that on webkit, maybe you have to set a breakpoint on your source code using the `debugger` statement. – bfavaretto Nov 21 '12 at 16:45