Scope and closure detail in javascript

  • 2020-12-07 03:58:50
  • OfStack

1. JavaScript scope

JavaScript variables actually have only two scopes, global variables and function internal variables. A variable defined anywhere within a function (var scope) is scoped to the entire function body.
Global variables: Refer to the object properties under the window object.
Scoped: Context-based, demarcated by functions rather than by blocks.
Emphasize two points:
1. In the same 1 scope, JavaScript is allowed to duplicate definitions of variables, and the latter definition overrides the former.
2. Variables defined within the function without the keyword var are default global variables.


var scope="global"; 
function t(){ 
  console.log(scope); //"global" 
  scope="local" 
  console.log(scope); //"local" 
} 
t(); 
console.log(scope); //"local" 




var scope="global"; 
function t(){ 
  console.log(scope); //"undefined" 
  var scope="local" 
  console.log(scope); //"local" 
} 
t(); 
console.log(scope); //"global" 

During variable resolution, the local scope is first looked up, then the upper scope is looked up. The variable scope is not defined in the function in section 1, so the upper scope (global scope) is looked up and its value is output. But the variable scope is defined in the function in the second section of the code (the variable defined after or before console is considered to have the variable scope in this scope), so instead of looking up in the upper scope, scope is simply output. Unfortunately, the local variable i is not assigned, so undefined is output.


// So depending on the scope of the function, you can put the above number 2 The code is rewritten as follows:  
var scope="global"; 
function t(){ 
  var scope; 
  console.log(scope); 
  scope="local" 
  console.log(scope); 
} 
t(); 

Because of the scoped nature of the function, local variables are always defined throughout the body of the function, and we can declare variables "ahead" to the top of the body.


var b; // The first 1 step  
function fun(){  
  b = "change";  
}  
alert(b);// The output undefined , as a result of the first 1 A step defines only an unassigned value  
 
 
var b; // The first 1 step  
function fun(){  
  b = "change";  
} 
fun(); // Call the above function  
alert(b); // The output change 

When a variable is declared using var, the property created is not configurable, meaning that it cannot be removed by the delete operator.
2. Scope instance


<html> 
<head> 
  <script type="text/javascript"> 
    function buttonInit(){ 
      for(var i=1;i<4;i++){ 
        var b=document.getElementById("button"+i); 
        b.addEventListener("click" . function(){ alert("Button"+i);} . false); 
      } 
    } 
    window.onload=buttonInit; 
  </script> 
</head> 
<body> 
  <button id="button1">Button1</button> 
  <button id="button2">Button2</button> 
  <button id="button3">Button3</button> 
</body> 
</html>

When the registration event is over, the value of i is 4. When the button is clicked, the event function is function(){alert("Button"+i); } There is no i in this anonymous function, according to the scope chain, so go to buttonInit function to find, at this time the value of i is 4, so pop "button4".
3. javaScript closures
In js, closures are primarily concerned with several other features of js: scope chains, garbage (memory) collection mechanisms, function nesting, and so on.
: 1. The scope chain in simple terms, the scope chain is the time to create function has been defined and used to find using an index of the value of a variable, and his internal rule is that the function of its own local variables on the front, put their own parent function variables in second, the next higher level 1 a variable in a function in more behind, and so on until global objects. When the value of a variable needs to be queried in the function, the js interpreter will go to the scope chain to look for it, first look for it from the local variable in the first place, if no corresponding variable is found, then look for it on the chain in the next level, once the variable is found, it will not continue. The interpreter returns undefined if the desired variable is found and is not found.
2. Javascript's garbage collection mechanism: In Javascript, if an object is no longer referenced, it is collected by GC. If two objects reference each other and are no longer referenced by third party, then the two objects that reference each other are also recycled. Because the function a is referenced by b, and b is referenced by c outside of a, this is why the function a is not recycled after execution. Building a closure, these variables will not be collected by the memory collector, the closure will be destroyed only when the internal function is not called, and variables that do not have any references to a closure will be collected when the next memory collection is started.
3. With closures, nested functional structures can work
4. Implement circular binding events using js closures


<html> 
<head> 
  <title> closure </title> 
</head> 
<body> 
  <ul id="list"> 
    <li> The first 1 records </li> 
    <li> The first 2 records </li> 
    <li> The first 3 records </li> 
    <li> The first 4 records </li> 
    <li> The first 5 records </li> 
    <li> The first 6 records </li> 
  </ul> 
  <script type="text/javascript"> 
    function tt(nob) { 
      this.clickFunc = function() { 
        alert(" This is the first " + (nob + 1) + " record "); 
      } 
    } 
    var list_obj = document.getElementById("list").getElementsByTagName("li"); // To obtain list All of the following li Array of objects  
    for (var i = 0; i<= list_obj.length; i++){ 
      console.log(list_obj[i]) 
      list_obj[i].onmousemove = function(){ 
        this.style.backgroundColor = "#cdcdcd"; 
      } 
      list_obj[i].onmouseout = function() { 
        this.style.backgroundColor = "#FFFFFF"; 
      } 
      //list_obj[i].onclick = function() { 
      // alert(" This is the first " + i + " record "); // Can't get properly  alert All that came out were: "This is number one 6 Record"  
      //} 
      var col = new tt(i); // call tt function  
      list_obj[i].onclick = col.clickFunc; // perform clickFunc function  
    } 
  </script> 
</body> 
</html> 

That's the end of this article and I hope it will be helpful for you to learn javascript programming.


Related articles: