I have an anonymous function that's attached to an event listener in Chrome, how can I inspect the values of its closure?
我有一个匿名函数附加到Chrome中的事件监听器,我如何检查其闭包的值?
For example:
例如:
(function(){
var i = 0;
document.body.onclick = function() {
i += 1;
};
})();
How can I find the current value of i?
我怎样才能找到i的当前值?
1 个解决方案
#1
4
Unfortunately, if you just try to look in the Chrome console at it for this example, you won't find it easy to see, you'll just get the function body:
不幸的是,如果您只是尝试在Chrome控制台中查看此示例,您将看不到它很容易看到,您只需获取功能正文:
> document.body.onclick
function () {
i += 1;
}
And looking at document.body alone gives you a DOM tree inspector, not a Javascript object view.
看一下document.body就可以给你一个DOM树检查器,而不是Javascript对象视图。
So do this:
这样做:
a = { f: document.body.onclick }
And you'll get an object output line in the console, with a disclosure triangle that you can open, then open the f
field, and you'll see a <function scope>
you can open, finally revealing a Closure
you can open.
你将在控制台中得到一个对象输出行,你可以打开一个显示三角形,然后打开f字段,你会看到一个
For differently-registered event listeners or other ways functions can hang around (timers, etc.), it can be challenging to find references to the functions that allow you to do this. In Chrome, if addEventListener was used, you can use a console function called getEventListeners(element).
对于不同注册的事件监听器或函数可以挂起的其他方式(定时器等),找到允许您执行此操作的函数的引用可能具有挑战性。在Chrome中,如果使用了addEventListener,则可以使用名为getEventListeners(element)的控制台函数。
#1
4
Unfortunately, if you just try to look in the Chrome console at it for this example, you won't find it easy to see, you'll just get the function body:
不幸的是,如果您只是尝试在Chrome控制台中查看此示例,您将看不到它很容易看到,您只需获取功能正文:
> document.body.onclick
function () {
i += 1;
}
And looking at document.body alone gives you a DOM tree inspector, not a Javascript object view.
看一下document.body就可以给你一个DOM树检查器,而不是Javascript对象视图。
So do this:
这样做:
a = { f: document.body.onclick }
And you'll get an object output line in the console, with a disclosure triangle that you can open, then open the f
field, and you'll see a <function scope>
you can open, finally revealing a Closure
you can open.
你将在控制台中得到一个对象输出行,你可以打开一个显示三角形,然后打开f字段,你会看到一个
For differently-registered event listeners or other ways functions can hang around (timers, etc.), it can be challenging to find references to the functions that allow you to do this. In Chrome, if addEventListener was used, you can use a console function called getEventListeners(element).
对于不同注册的事件监听器或函数可以挂起的其他方式(定时器等),找到允许您执行此操作的函数的引用可能具有挑战性。在Chrome中,如果使用了addEventListener,则可以使用名为getEventListeners(element)的控制台函数。