Closure

by charmis

HTML

<input type=button value='click me' onclick='javascript:Outer()'>

JavaScript

function sayHello2(name) {
  var text = 'Hello ' + name; // local variable
  var sayAlert = function() { alert(text); }
  return sayAlert;
}
var outerReferenceToFunction;
function say667() {
  // Local variable that ends up within closure
  var num = 666;
  outerReferenceToFunction = function() { alert(num ); num ++; }
 num++;  
}


function PrintNames()
{
    var firstName = 'charmis';
    var lastName = ' Poovan Varghese';
    
    function PrintFullName()
    {
        alert(firstName + ' ' + lastName);
    }
    
    function PrintFirstName()
    {
        alert(firstName);
    }
    
    function PrintLastName()
    {
        alert(lastName);
    }
    
    return function() { 
        var userChoice=prompt("1,2,3")
if (userChoice==1)
  {
  PrintFirstName();
  }
else if(userChoice==2)
  {
  PrintLastName();
  }
   else if(userChoice==3)
  {
  PrintFullName();
  }         
            
    }
}


function Outer()
{
//say2 = sayHello2('Bob');
//say2 = say667();
//say2 = setupSomeGlobals();    
//say2(); 
//say2(); 
//say3 = say667();
//    say3();
    //say667();
    //outerReferenceToFunction();
        PrintNames()();
}

function setupSomeGlobals() {
  // Local variable that ends up within closure
  var num = 666;
  // Store some references to functions as global variables
  gAlertNumber = function() { alert(num); }
  gIncreaseNumber = function() { num++; }
  gSetNumber = function(x) { num = x; }
      
      return gIncreaseNumber;
}