Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I inspect an anonymous function closure in Chrome

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?

like image 837
Tim Dierks Avatar asked Oct 01 '22 18:10

Tim Dierks


1 Answers

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).

like image 191
Tim Dierks Avatar answered Oct 04 '22 12:10

Tim Dierks