关于JavaScript变量的Scope

1 var sth = ""; // Global Scope

2 var foo = function(){

  var sth = ""; // Local Scope

}

3 var foo = function(){

  sth = ""; // Global Scope, this is definitely denied!

}

4 (function(){

  var jQuery = {

    // variable methods or definitions  

  }

  window.jQuery = jQuery;

})(); // Immediately-Invoked Function Expressions, This is used by jQuery and some other liberaries.

point1: the var exsits in var jQuery is very important, without it jQuery will be global scope.

point2: though the jQuery is also global scope, but when another jQuery defined in window, it will also work.

according to http://learn.jquery.com/javascript-101/scope/

5 closure

for(var i=0;i<5;i++){

  setTimeOut(function(){

    alert(i);  // will not alert correctly~, because the i has already added for 5 times in the fiven 1000 mill-seconds.

  }, 1000);

}

to correct this, we should use closure.

for (var i=0;i<5;i++) {

  setTimeOut(alertFunc(i), i*1000); // why? the function will be called immediately with parameter i, so the alertFunc knows that i, and only i nothing else, then alert 0, 1, 2, 3, 4, end~

}

var alertFunc = function(i){

  alert(i);

}

according to http://learn.jquery.com/javascript-101/closures/

原文地址:https://www.cnblogs.com/voctrals/p/3706618.html