In layman's JavaScript closure (Closure)

Source: Internet
Author: User

Closures (closure) are a very important threshold for mastering JavaScript from the human door to the deep, which is a difficult and characteristic of the JavaScript language, and many advanced applications rely on closures.

closures-Everywhere

In front-end programming, the use of closures is very common, we often intentionally or unintentionally, directly or indirectly using the closure. Closures can make passing data more flexible (such as handling some click events)

!function () {var localdata = "Localdata here";                         Document.addeventlistener (' click ',////handles the Click event with an external local variable, such as the Localdata  function () { Console.log (Localdata);  

Another example of the following: (is not very kind ~ ~)

!function () {var localdata = "Localdata here";        var url = "http://www.baidu.com/"; $.ajax ({  url:url, success:function () {//do STH ... co       Nsole.log (localdata);  }  }); }();

One more example of this is what we usually call closures.

function outer () {  var localval = 30;      return function () {return localval;  }} var func = outer (); Func (); 30

In this example, call outer () returns an anonymous function (), which can access the local variable localval of outer (), and still have access to outer () after the outer () call is over, calling Func () again. The local variable Localval

The concept of closures

Closures, unlike general functions, allow a function to access a non-local variable when it is called outside of an immediate lexical domain. --Wikipedia

Closures are functions that can read other functions ' internal variables. --Ruan Yi Feng

Because in the JavaScript language, only sub-functions inside the function can read local variables, it is possible to simply interpret the closure as "a function defined inside a function".

So, in essence, a closure is a bridge that connects the inside of the function to the outside of the function.

use of closures

This part is transferred from this blog post

Closures can be used in many places. Its maximum usefulness is two, one of the previously mentioned variables that can read the inside of a function, and the other is to keep the values of these variables in memory at all times.

Function F1 () {var n=999;    Nadd=function () {n+=1} function F2 () {alert (n);  } return F2;  } var result=f1 (); Result ();  999 Nadd (); Result (); 1000

In this code, result is actually the closure F2 function. It runs altogether two times, the first value is 999, the second value is 1000. This proves that the local variable n in the function F1 is kept in memory and is not automatically cleared after the F1 call.

Why is that? The reason is that F1 is the parent function of F2, and F2 is assigned to a global variable, which causes F2 to always be in memory, and F2 's presence depends on F1, so F1 is always in memory and will not be reclaimed by the garbage collection mechanism (garbage collection) after the call ends.

Another notable part of this code is the line "nadd=function () {n+=1}", which first did not use the var keyword in front of Nadd, so Nadd is a global variable, not a local variable. Second, the value of Nadd is an anonymous function (anonymous functions), and the anonymous function itself is a closure, so nadd is equivalent to a setter that can manipulate local variables inside the function outside of the function.

Closures-Package
(function () {  var _userid = 23492;        var _typeid = ' item ';      var export = {};  function Converter (userId) {return +userid;  }  Export.getuserid = function () {  return converter (_userid);   }  Export.gettypeid = function () {return _typeid;  }  window.export = Export;  Output} () in this way); Export.getuserid ();  23492  Export.gettypeid ();    Item  Export._userid;    Undefined Export._typeid; Undefined  export.converter;//undefined

The closure feature allows us to encapsulate some complex function logic, in which the method (Getuserid,gettypeid) on the export is called to indirectly access the private variable in the function, but the direct call to Export._userid is impossible to get _userid. This is also the use of node inside the feature bar ~

cyclic closure of common errors

In this case, we add 3 div, the value is AAA,BBB,CCC, we want to achieve is click on the AAA Output 1, click on the BBB Output 2, click on the CCC output 3

Document.body.innerHTML = "<div id=div1>aaa</div>" + "<div id=div2>bbb</div><div id=div3  >ccc</div> ";        for (var i = 1; i < 4; i++) {document.getElementById (' div ' + i).     addeventlistener (' click ', Function () {  alert (i);//All is 4!  }); }

Results Click AAA,BBB or CCC are alert (4) ~ ~

The problem is that the value of I is already 4 when the initialization is complete.

To achieve what we want to click on the AAA Output 1, click on the BBB Output 2, click on the CCC output 3, to use the closure of the technique, in each loop, with the immediate execution of the anonymous function to wrap it up, this way, each alert (i) value is taken from the closure environment of I, This I come from the assignment of each cycle I can output a.

Document.body.innerHTML = "<div id=div1>aaa</div>" + "<div id=div2>bbb</div>" + "<div id=  Div3>ccc</div> ";  for (var i = 1; i < 4; i++) {!function (i) {//② Then use this parameter I, getElementById () to refer to  document.getElementById (' div ' +    i).  addeventlistener (' click ', Function () {  alert (i);///);  } (i); ① to pass the value of the traverse to the anonymous function}

Study Questions

If you can understand the results of the following two sections of code, you should understand the operation mechanism of the closure. (from teacher Ruan) This topic summed up real second ~ ~

Code snippet one.

var name = "the window";      var object = {Name: "My Object", Getnamefunc:function () {return function () {return this.name;    };  }  }; Alert (Object.getnamefunc () ());

Code snippet two.

var name = "the window";      var object = {Name: "My Object", Getnamefunc:function () {var = this;      return function () {return that.name;    };  }  }; Alert (Object.getnamefunc () ());

Via:http://www.cnblogs.com/muyunyun/p/5930703.html

In layman's JavaScript closure (Closure)

Related Article

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.