Reputation: 533
I was trying out a very basic example of Javascript closure, but I am not able to visualize it in Chrome devtools. Please see the screenshot.
I have created a global variable
var p = 3;
and a function
function f1() {
var q = 2;
return p+q;
}
This function is using the global variable p
inside it, so this is a closure, right? Please guide me if my understanding is not correct.
So, if this is a closure then why doesn't it shown in the function scope as "Closure"?
Upvotes: 4
Views: 3381
Reputation: 1520
w3schools.com says "A closure is a function having access to the parent scope, even after the parent function has closed." In your example, p is defined in the global scope, not a parent function. If you wrap your code in a parent function, in the dev tools, you will see p listed under closure.
var f2 = function(){
var p = 3;
var f1 = function(){
var q = 2;
return p + q;
}
return f1;
}();
console.dir(f2);
Upvotes: 5