I would like to see the content of a closure in JavaScript.
In the following code, I would like to see the closure of the function closure_f
returned by the anonymous function. The local scope of the anonymous function must be stored somewhere, I would like to see where it is stored. How can this be done in Node or in the browser?
var closure_F = (function(){
var info = "info-string";
var f1 = function(){
console.log(info);
};
return f1;
}());
closure_F(); // logs 'info-string' as expected.
console.log(closure_F); // This did not provide any valuable information.
WAY 1: Internal property [[Scope]]
You can modify your code by adding console.dir
and then run it in the Chrome Dev Console:
var closure_F = (function(){
var info = "info-string";
var f1 = function(){
console.log(info);
};
return f1;
}());
closure_F();
console.dir(closure_F);
// console.dir prints all the properties of a specified JavaScript object
If you open the console you will see that it prints all the properties of the object (function), including the internal property [[Scopes]]
.
This internal property [[Scopes]]
will contain any surrounding scopes of the closure_f
, and its closure. See example:
Note: [[Scope]]
is an internal implementation of JS and cannot be programatically accessed within the program.
WAY 2: Setting a breakpoint - debugger
Another way to see the Closure of a function is to add a debugger
statement and create a break point in the function who's closure you want to inspect.
As an example you can run this in the console:
function createClosure (){
var secret = "shhhhh";
return function inner(){
debugger;
console.log(secret);
};
};
var innerFunction = createClosure();
innerFunction();
www.ecma-international.org >> [[Scope]] >> Table 9
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