[英]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
. 当然, A
不会最终成为window
的属性。 Is it perhaps a property of the anonymous function object which spans lines 2 thru 5999? 它可能是跨越2行到5999行的匿名函数对象的属性吗? So if I name the function so I can reference it am I able to use watch
on the A
var/prop somehow? 因此,如果我命名该函数以便可以引用它,那么我是否可以以某种方式在A
var / prop上使用watch
?
What other methods are available to me to figure out where the var gets set? 我还有哪些其他方法可以确定var的设置位置?
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. 这将其拉入全局区域,并应允许您从全局变量ox观察变量x。
You can't use Object.prototype.watch
on that variable, simply because it's a variable, not an object property. 您不能在该变量上使用Object.prototype.watch
,仅仅是因为它是一个变量,而不是对象属性。 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. 如果您出于调试目的而尝试这样做,我相信您可以从浏览器的开发人员工具中进行观察。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.