|
|
|
|
|
by chrismear
6063 days ago
|
|
I've found that the concept of anonymous functions is the biggest hurdle to get over -- closures seem to follow as a natural extension of that. I explained this to someone recently in the context of event handlers in ActionScript/JavaScript, starting with the idea that when you do: something.onclick = function(){...};
you're passing a function around just like it was any other value.Then I moved to an artificial example of a 'magic function-making machine': function giveMeAnAdder(baseNumber) {
return function (i) {
return baseNumber + i;
};
}
with a couple of examples of storing and using the functions that giveMeAnAdder returns.Then I pointed out that, normally, local variables in a function disappear when the function returns, so how does my adder 'remember' what baseNumber is? And the answer is that the anonymous function is actually a bundle of a function body and the local context, and we call this a closure. |
|
Why do you want me to appreciate a ferrari if all you do with it is go pick up some groceries...