I have an anonymous function that's attached to an event listener in Chrome, how can I inspect the values of its closure?
For example:
(function(){
var i = 0;
document.body.onclick = function() {
i += 1;
};
})();
How can I find the current value of i?
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:
> document.body.onclick
function () {
i += 1;
}
And looking at document.body alone gives you a DOM tree inspector, not a Javascript object view.
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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With