"turn" 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. below, write down my study notes ~

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)

1234567 !function() {        var localData = "localData here";         document.addEventListener(‘click‘,    //处理点击事件时用到了外部局部变量,比如这里的localData               function(){                         console.log(localData);     }); }();

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

1234567891011 !function() {        var localData = "localData here";        var url = "http://www.baidu.com/";        $.ajax({      url : url,               success : function() {                      // do sth...                      console.log(localData);         }     }); }(); 

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

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

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.

123456789101112 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
12345678910111213141516171819202122 (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;   //通过此方式输出}());  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

1234567 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 are 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.

123456789 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){ //②再用这个参数i,到getElementById()中引用         document.getElementById(‘div‘ + i).             addEventListener(‘click‘, function() {               alert(i); // 1,2,3     });    }(i);  //①把遍历的1,2,3的值传到匿名函数里面

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.

12345678910 var name = "The Window";var object = {  name : "My Object",  getNameFunc : function(){    return function(){      return this.name;    };  }};alert(object.getNameFunc()());

Code Snippet Two.

1234567891011 var name = "The Window";var object = {  name : "My Object",  getNameFunc : function(){    var that = this;    return function(){      return that.name;    };  }};alert(object.getNameFunc()());

"go" 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.