A brief description of JavaScript scoped closures

Source: Internet
Author: User

A brief description of JavaScript scoped closures

Scope

The general level of technology is limited, there is nothing wrong, I hope you correct.

Scopes are the scopes in which variables Work. Scopes include global scopes, function scopes at Block-level scope, and let and const in ES6 can form Block-level scopes.

In addition to Block-level scopes, variables declared outside the function can be accessed anywhere, and the scope of these variables is global scope, and variables in the global scope can be used anywhere else:

var a = "zt"; function fn1 () {    console.log (a);} function fn2 () {    console.log (a);} FN1 (); fn2 ();

Variables declared inside a function can only be used within the current function, and the scope of these variables is called the function scope and is valid only within the current function:

function Fn1 () {    var a = "zt";    Console.log (a);} function fn2 () {    console.log (a)}fn1 (); fn2 ();//error hint a not defined

The variables defined within the function are valid only within the current function and cannot be accessed outside of the function, and a is not defined within the FN2 function, and A is not present in the global scope, and a non-existent variable is used for the Error.

Scope chain

Scopes can be nested, such as creating a function within a global scope, in which a function can be created in which the scope is nested, and the scope chain can link the Scope. When a variable is used, it takes precedence over the current scope to find the variable, and if it does not exist in the current scope, it will go to the upper scope to find the global scope, and if the variable cannot be found, it will be an Error.

var a = "global"; function fn1 () {    console.log (a);} FN1 ();

The scope is static

Let's look at an example first:

  var flag = "outer";  Function Demo () {      var flag = "inner";      function inner () {          console.log (flag);      }      return inner;  }  var fn = Demo ();  FN ();//inner
  var flag = "outer";  Function Demo () {      var flag = "inner";      fn ();  }  FUNCTION fn () {      console.log (flag);  }  Demo ();//outer

With these two examples we can see that the scope of the function is static, where a function is called, and its scope is the scope of the Declaration. The scope of the function is created at the time of declaration, and when the function is called, it accesses the scope that he has created.

Closed Package

Closures are defined in the MDN as closures refer to functions that can access independent variables, so we can consider all functions as closures in the Definition. Closure is confined space, we can naturally think of the function, because the function will generate a confined space, if the function is to call a closure only need to use an external variable (the function that uses the external variable is the closure). Closures can give us the convenience of using variables in a low-level scope at a high level of scope:

  Function Demo () {      var flag = "test";      return function () {          console.log (flag);      }  }  Demo () ();

We put the function inside the demo function through return so that it can be used externally, we have said that the scope is static, so we use the return function externally, we can see that we call the function in the global scope finally output the "test" inside the demo Function.

So we can do something more meaningful:

  var data = [];  Function Demo () {      var data = [];      return{          add:function (a) {              data.push (a);          },          print:function () {              console.log (data);  }}  var tool = Demo ();  Tool.add (1);  Tool.add (2);  Tool.add (3);  Tool.print ();//[1, 2, 3]

We can use the data in the demo function to store our information without worrying about it being destroyed (the data in the demo is privatized), and we can also externally declare a data of the same name to store other information without any conflict between the Two.

Closures can also help us solve some minor problems:

  For (var i=0;i<4;i++) {      setTimeout (function () {          console.log (i);      });  }

Our expected result is that the output of the I-value results for the current loop is all 4. First explain the reasons for this situation: JS is a single-threaded language, and settimeout is asynchronous, only when our code execution is completed after the settimeout processing function will be executed, and the execution of the value of I is already 4, so the final output is all 4.

We can solve this problem by closing the package:

  For (var i=0;i<4;i++) {      (function (i) {          setTimeout (function () {              console.log (i)}          )      } (i)  }

Closures can form a separate scope so that each loop has a separate function scope, and although the value of I is still 4 after the loop is completed, the settimeout processing function will first find I as the parameter when I is searched, and each parameter I represents the I of the second cycle, We can solve this problem perfectly by using Closures.

In our actual development process, we can solve this situation through closures, we say "this situation" usually has three characteristics:

1. First there is a cycle

2. The function is created in the loop, and the function is deferred

3. These deferred functions use a common variable, and this common variable is related to the current loop value

Let's set up the above code according to this rule:

Loop has, each cycle will also generate a function, these functions are not executed after the loop is completed, and each function uses a common i, and I is the current loop value, exactly in line with our three Characteristics. We do this by (function () {} ()) (anonymous function Self-executing) to form a closure to achieve our intended purpose.

A deeper understanding of the relevant information can be found on the Internet.

Reproduced from the network

A brief description of JavaScript scoped closures

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.