Wednesday, June 23, 2010

Java Script Anonymous functions , Closures

People have doubts about closures and anonymous functions. actually closures are a type of function which allow the creation of functions which have no specified name. they are very useful when you want control over callback or you want use function as the values of variables. every language provide a freedom to create anonymous/closures functions. PHP also provide such feature .. 

$greet = function($name)
printf("Hello %s\r\n"$name);

Back to our discussion. here, i summarized about js anonymous, closures. 

Anonymous functions
  • Any function that is defined as a function expression is technically an anonymous function since there is no definitive way to reference it.
  • With no definitive way to reference a function, recursive functions become more complicated.
  • Recursive functions should always use arguments.callee to call themselves recursively instead of using the function name, which may change.
Closures are created when anonymous functions are defined inside other functions, allowing the closure access to all of the variables inside of the containing function, as follows:-
  • Behind the scenes, the closure ’ s scope chain contains a scope for itself, a scope for the containing function, and the global scope.
  • Typically a function ’ s scope and all of its variables are destroyed when the function has finished executing.
  • When a closure is returned from that function, its scope remains in memory until the closure no longer exists.
Using closures, it ’ s possible to mimic block scoping in JavaScript, which doesn ’ t exist natively, as follows:-
  • A function can be created and called immediately, executing the code within it but never leaving a reference to the function.
  • This results in all of the variables inside the function being destroyed unless they are specifically set to a variable in the containing scope.
Closures can also be used to create private variables in objects, as follows:-
  • Even though JavaScript doesn ’ t have a formal concept of private object properties, anonymous functions can be used to implement public methods that have access to variables defined within the containing scope.
  • Public methods that have access to private variables are called privileged methods.
  • Privileged methods can be implemented on custom types using the constructor or prototype patterns as well as on singletons by using the module or module - augmentation patterns.
  • Anonymous functions and closures are extremely powerful in JavaScript and can be used to accomplish many things. Keep in mind that closures maintain extra scopes in memory, so overusing them may result in increased memory consumption.
original source  from Nicholas C. Zakas (Yahoo's principal front-end engineer) 

No comments:

Post a Comment