[Javascirpt] Immediately-Invoked function!!! IMPORTANT

var parkRides = [["Birch Bumpers", 40], ["Pines Plunge", 55],
                 ["Cedar Coaster", 20], ["Ferris Wheel of Firs". 90]];
                
var fastPassQueus = ["Cedar Coaster", "Pines Plunge", "Birch Bumpers", "Pines Plunge"];

var wantsRide = "Birch Bumpers";
/*Now we store the function in a variable*/
var ticket = buildTicket(allRides, passRides, wantsRide);
ticket(); //call the function, we need a () and ;

/*Javascript has an immediately-invoked function*/
var wantsRide = "Cedar Coaster";
//This time we get ride of the ticket variable
//and we just call the buildTicket function without return anything
buildTicket(allRides, passRides, wantsRide);
/**
//What it returns is the whole body of the function only 

(function(){alert("Quick! You've got a Fast Pass to "+ pass +"!"))

//We got the function expression, but we need more to call this
//function expression immediately.
*/

buildTicket(allRides, passRides, wantsRide)();
/**
(function(){alert("Quick! You've got a Fast Pass to "+ pass +"!"))();

//Then it will call the function expression
*/

function buildTicket(allRides, passRides, pick){
    if(passRides[0]==pick){
        var pass = passRides.shift();
        return function(){alert("Quick! You've got a Fast Pass to "+ pass +"!");};        
    }else{
        for(vari = 0; i < allRides.length; i++){
            if(allRides[i][0]==pick){
                return function(){alert("A ticket is printing for "+ pick + "!\n" +
                                        "Your wait time is about "+ allRides[i][1]+ "minutes.");};
            }
        }
    }
}

 

Tow ways to call a function expression immediately. 

1. var ticket = buildTicket(allRides, passRides, wantsRide);

    ticket(); //call the fucntion here!

2.  buildTicket(allRides, passRides, wantsRide)();  //Without store function in a variable!!!

 

 

-------Example------

function adventureSelector ( userChoice ){
  switch(userChoice){
    case 1:
      return function(){
        alert('You\'ve selected the Vines of Doom!'
             + "\n" +
             'Hope you have a swingin\' time.');};
    case 2:
     return function(){
           alert('Looks like you want the Lake of Despair!'
              +"\n"+
              'Watch out for crocs. And I ain\'t talkin\' about shoes.');
      };
    case 3:
      return function(){
        alert('The Caves of Catastrophe, really?'
             +"\n"+
              'Alright, well....nice knowing you.'
             );};
    default:
      break;
  }
}

adventureSelector(1)();

 

posted @ 2014-08-02 19:50  Zhentiw  阅读(209)  评论(0编辑  收藏  举报