Reputation: 30163
I am tasked to trace the cause of a memory leak in one of our applications so I'm trying to study closures. I wonder if this code creates closure:
function foo(p)
{
return function(){ return p + 1; }
}
Based on my understanding, closure is created when the inner function gains access to a local variable of its parent function. The parameter p
is local to foo
, if the inner function gains an access to p
, does it mean a closure is created?
Upvotes: 1
Views: 65
Reputation: 25062
This does create a closure, but it is not the typical closure that is talke about in javascript. What is the typical example is:
var adder = function(a) {
return function(b) {
return a + b;
}
}
What this does is give you the ability to create a "closure" or close in a variable to be used over and over again. I can create a function:
var adder4 = adder(4);
Now if I want to add 4 to any number I can user adder4(2)
and the result in this case would be 6
. What is going on here is that the 4
is inserted for the variable a
. The variable a
is then enclosed inside this function permanently. We can then replace the variable b
at any time to create a new function. So when I made the function call adder4(2)
, I am using a function in which a
has already been assigned. The variable 2
in that case is assigned to the variable b
. Obviously when you add 4
and 2
you get 6
. But you can use the same function to add another number, adder4(3). Now this does the same logic and gives you 7
. The 4
is still enclosed, or in the "closure", but you are free to replace another variable in the middle of the function.
You also see this a lot with anonymous functions and click handlers, but you can google that for much better answers.
Hope this helps.
Upvotes: 0
Reputation: 388446
The parameters of a function exists in the local scope of the function, so yes it creates a closure
Upvotes: 1
Reputation: 16470
Yes, that is exactly what's happening here. The inner function you're returning has access to the parameter p
through the local scope, so you're correct.
It would also have created a closure if you referenced a local variable from the outer function in the returning function, like that:
function foo(p) {
var q = 4;
return function() { return p + q; }
}
Here's a very detailed explanation: Explaining JavaScript Scope And Closures
Upvotes: 1