[Javascript] Funciton Expression

//This will load the code into the memory no matter 
//you call it or not
function diffOfSquares(a,b){
    return a*a -b*b;
}

//This code will only load into memory when you call it.
var diff = function diffOfSquares(a,b){
    return a*a-b*b;
};

diff(9,5); //Call diff function instead of diffOfSquares 

//So why we still need diffOfSquares, since we don't call it

/**
    Anonymour Function
*/
var diff = function(a,b){
    return a*a-b*b;
};

//You can use console.log(diff); It will print out the
//function instead of the value, so you can check what
//this function refer to.

/********************************************/

var greeting = function(){
    alert("Thank for fucking!");
};

closeTerminal(greeting);

function closeTerminal(message){
    
    ...
    message();
    ....
}

//We pass greeting as param to the closeTerminal function
/*
    function closeTerminal(greeting){
        ...
        greeting();
        ...
    }
*/
//The out put would be 
//"Thank for fucking!"


/*********************************************/
//According to difference cases, the greeting message 
//may be different.
//For example, newCustomer & oldCustomer, we want to 
//take them differently.

var greeting;
... //Some code to sets new newCustomer to ture of false
if(newCustomer){
    greeting = function(){
        alert("Thanks for funcking!");
    };
}else{
    greeting = function(){
        alert("Welcome to be fucked!");
    };
}

closeTerminal(greeting);
//if newCustomer is true, --> Thanks for funcking!
//if newCustomer is false, --> Welcome to be fucked!

 

posted @ 2014-08-02 16:37  Zhentiw  阅读(193)  评论(0编辑  收藏  举报