by http://webgeektutorials.blogspot.com

Friday, September 5, 2014

Javascript: Introduction to Anonymous functions


Anonymous functions are functions that are dynamically declared at runtime that don’t have to be given a name.

Anonymous functions are declared using the function operator. You can use the function operator to create a new function wherever it’s valid to put an expression. For example you could declare a new function as a parameter to a function call or to assign a property of another object.

Example of a non-anonymous function:
function dosomething(){

    var b = 3;
    a += b;
    return a;
}


Example of a anonymous function:
var dosomething = function(){
    var b = 3;
    a += b;
    return a;
};

dosomething();

Logically they are the same. However, the second one is an expression, an anonymous function assigned to a variable 'dosomething'; The first one is a function declaration, but the second one is a function expression.
It's got the parenthesis around it (and trailing) so that the function is called immediately.

The most common use for anonymous functions are as arguments to other functions, or as a closure.

setTimeout(function() {
    dosomething();
}, 1000);

// Our anonymous function is passed to setTimeout, which will execute
// the function in 1000 milliseconds.

Anonymous functions are used for the reasons of:
a) code brevity: It often makes sense to use anonymous functions calls in callbacks and event handlers;
b) scope management: Anonymous functions can be used to create temporary/private scope;
c) Anonymous function are often handy in closures and recursions.

Recursions : Recursions are functions that call themselves, they are often used to solve problems such as factorials, the tower of hanoi, golden ratio (See wiki Recursion. Or, fibonacci numbers. 
 function fibonacci(n) {
    if (n < 2)
        return n;

    return fibonacci(n - 1) + fibonacci(n - 2);
}

alert(fibonacci(6)); //8

It works fine. But it can/should be improved with two things: arguments.callee and function memorization. As the following:

 function f(n) {
 
    if (n < 2)
        return n;

    if (f.answers[n] != null)
        return f.answers[n];

    f.answers[n] = arguments.callee(n - 1) + arguments.callee(n - 2);

    return f.answers[n];
}

f.answers ={};

var fibo = f;
alert(fibo(10)); //55
alert(fibo(11)); //89



Source :   http://helephant.com , http://jsninja.com

No comments:

Post a Comment