Pages

Tuesday, July 3, 2012

Function in JavaScript


Passing functions to another function
    function invoke_and_add(a,b){
        return a() + b();
    }

    function one(){
        return 1;
    }

    function two(){
        return 2;
    }

    invoke_and_add(one,two);

Callback function
    function multiplyByTwo(a,b,c, callback){
        var i, array = [];
        for(i=0;i<3; i++){
        array[i] = callback(arguments[i] * 2);
        }
        return array;
    }

    function addOne(a){
        return a+1;
    }

    myarr = multiplyByTwo(1,2,3,addOne);

Self-invoking function
    (
        function(){
            alert('this is a self invoking function');
        }
    )()

Inner (Private) function
    function a(param){
        function b(input){
        return input * 2;
        };
        
        return 'the result is ' + b(param);
    };

    a(2);

Functions that return function
    function a(){
        alert('a');
        return function(){
        alert('b');
        };
    }

    var newFn = a();
    newFn();

    // also the above 2 lines can be replaced with this one liner

    a()();


Function rewriting itself
    function a(){
        alert('a');
        a = function(){
        alert('b');
        };
    }

    a();
    a();

No comments:

Post a Comment