Returning functions
Functions are objects, so they can be passed around like callbacks for example and also returned by other functions.
You call a function that does some complicated setup and as a results returns a new function. You assign the result to a new function and use it afterwards.
function setup() { alert(1); return function() { alert(2); }; } var my = setup(); // alerts 1 my(); // alerts 2
Your setup function can store some private data in a closure and use that data somehow.
Here setup() creates a counter function, which gives a next ID for example. But the count variable is not exposed.
function setup() { var count = 0; return function() { return ++count; }; } var next = setup(); next(); // 1 next(); // 2
Tags: Functions
September 15th, 2009 at 2:18 pm
[...] Exploring common JavaScript patterns and anti-patterns « Returning functions [...]
February 23rd, 2011 at 8:21 pm
I just read through this part of your book, and I was a little confused with the second example and where the count variable was contained. I tried the example in the book and found that the count variable was in the global scope. And as I was writing this, I noticed that the example on this page is different, and works as explained.