Reputation: 18545
MDN's A re-introduction to JavaScript article finishes with a discussion of closures:
a function defined inside another function has access to the outer function's variables. The only difference here is that the outer function has returned, and hence common sense would seem to dictate that its local variables no longer exist.
The article goes on with scope objects and scope chain, etc. Sounds very sophisticated. However stepping thru their example script, I see no reason why common sense would fail?
function makeAdder(a) {
return function(b) {
return a + b;
};
}
var x = makeAdder(5);
var y = makeAdder(20);
x(6); // returns 11
y(7); // returns 27
So, setting x = to makeAdder with argument, 5:
x = function(b) {return 5 + b;};
so when we now call x with argument, 6, we have
function(6) {return 5 + 6;};
which returns 11.
I guess my question is: am I missing something? Closures seem simple. Why do people get hung up on the concept?
Upvotes: 2
Views: 82
Reputation: 11983
I find DOM element creation loops show the concerns best. Notice this code prints buttons with the correct i
values, but when clicked will show 5
because a new closure was not created capturing i
at the time.
for(var i = 0; i < 5; i++) {
var btn = document.createElement("button");
var t = document.createTextNode(i);
btn.appendChild(t);
btn.onclick=function(){ alert(i) }
document.body.appendChild(btn);
}
This code creates a new closure that will alert the correct value.
for(var i = 0; i < 5; i++) {
var btn = document.createElement("button");
var t = document.createTextNode(i);
btn.appendChild(t);
btn.onclick=onClick(i);
document.body.appendChild(btn);
}
function onClick(i) {
return function() { alert(i) }
}
Upvotes: 0
Reputation:
I guess my question is: am I missing something? Closures seem simple. Why do people get hung up on the concept?
No, you're not missing anything. Closures are simple. You'll have to ask the people who claim they're complicated—to the extent of even writing books on the topic—why they think they are.
What might conceivably be considered complicated is adopting a design mindset which takes advantage of this simple concept.
Upvotes: 1