简体   繁体   中英

Watching a variable in an anonymous function in JavaScript

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?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM