Anonymous functions

by jeremyjones on March 21, 2011

  • Share
  • CevherShare
  • Share

JavaScript allows the use of anonymous functions with full closures. Functions are objects and you can pass them as arguments just like any other object. The scope of a function includes all the names in the scope where it was declared. As you declare functions at run time and local variables can remain after the function returns, there are a number of closure options for coders.

Take this function for example:


var range = function (begin, end, jump) {

return function () {

var at = begin;
begin += jump;

if (at < end) return at;

else >throw >new Error ();
};
};

var next = range(0, 10, 2); /* range returns a function */

When you call next for the first time, it will return 0 and the next times it will return 2, 4, 6, and 8 and after that will throw an error. The local variables defined in range remain in memory until the next no longer exists. The function returns an anonymous function that is a closure and both the function code and the reference to the scope of the function were declared.

When the functions returns it holds the “function allocation record” range in memory and so the value of begin persists to the next time that you call next.

Leave a Comment

Previous post:

Next post: