Closures


A basic closure.
 var num = 10;

 function addNum(myNum){
   return num + myNum;
 }

 assert( addNum(5) == 15, "Add two numbers together, one from a closure." );

But why doesn't this work?
 var num = 10;

 function addNum(myNum){
   return num + myNum;
 }
 
 num = 15;

 assert( addNum(5) == 15, "Add two numbers together, one from a closure." );

Closures are frequently used for callbacks.
 var results = jQuery("#results").html("<li>Loading...</li>"); 

 jQuery.get("test.html", function(html){ 
   results.html( html ); 
   assert( results, "The element to append to, via a closure." ); 
 }); 

They're also useful for timers.
 var count = 0; 
  
 var timer = setInterval(function(){ 
   if ( count < 5 ) { 
     log( "Timer call: ", count );
     count++; 
   } else { 
     assert( count == 5, "Count came via a closure, accessed each step." ); 
     assert( timer, "The timer reference is also via a closure." ); 
     clearInterval( timer ); 
   } 
 }, 100); 

and they're also frequently used when attaching event listeners.
 var count = 1;
 var elem = document.createElement("li");
 elem.innerHTML = "Click me!";
 elem.onclick = function(){
   log( "Click #", count++ );
 };
 document.getElementById("results").appendChild( elem );
 assert( elem.parentNode, "Clickable element appended." );

Private properties, using closures.
 function Ninja(){ 
   var slices = 0; 
    
   this.getSlices = function(){ 
     return slices; 
   }; 
   this.slice = function(){ 
     slices++; 
   }; 
 } 
  
 var ninja = new Ninja(); 
 ninja.slice(); 
 assert( ninja.getSlices() == 1, "We're able to access the internal slice data." ); 
 assert( ninja.slices === undefined, "And the private data is inaccessible to us." ); 

QUIZ: What are the values of the variables?
var a = 5;
function runMe(a){
  assert( a == ___, "Check the value of a." );

  function innerRun(){
    assert( b == ___, "Check the value of b." );
    assert( c == ___, "Check the value of c." );
  }

  var b = 7;
  innerRun();
  var c = 8;
}
runMe(6);

for ( var d = 0; d < 3; d++ ) {
  setTimeout(function(){
    assert( d == ___, "Check the value of d." );
  }, 100);
}

The last one is quite tricky, we'll revisit it.
var a = 5;
function runMe(a){
  assert( a == 6, "Check the value of a." );

  function innerRun(){
    assert( b == 7, "Check the value of b." );
    assert( c == undefined, "Check the value of c." );
  }

  var b = 7;
  innerRun();
  var c = 8;
}
runMe(6);

for ( var d = 0; d < 3; d++ ) {
  setTimeout(function(){
    assert( d == 3, "Check the value of d." );
  }, 100);
}

[b]Temp

你可能感兴趣的:(java,jquery,C++,c,C#)