JavaScript closures Simple Comprehension

Source: Internet
Author: User
Tags variable scope

When it comes to closures, it must have been heard, and my simple understanding follows.
To tell the truth, there are not many scenes of actual manual closures in the work, but the third-party frameworks and components used in the project are more or less used in closures.
Therefore, it is very necessary to understand closures. Oh...

One, what is closures
In short, it is the function that can read the variables inside other functions .
Due to the nature of the JS variable scope, external variables cannot be accessed externally, and external variables can be used internally.

Second, the use of the scene
1. Implement a private member.
2. Protect namespaces and avoid polluting global variables.
3. Cache variables.

Let's look at an example of encapsulation:

varperson =function () {    //variable scope is inside function, external unreachable    varName = "Default"; return{getName:function () {            returnname; }, SetName:function(newName) {name=NewName; }}} (); Console.log (Person.name); //Direct access, the result is: undefinedConsole.log (Person.getname ());//The result is: DefaultConsole.log (Person.setname ("LANGJT") ); Console.log (Person.getname ()); //The result is: LANGJT

Then look at common closures in loops to solve the problem of referencing external variables:

var aLi = document.getelementsbytagname (' li ');  for (var i=0, len=ali.length; i<len; i++) {   function() {     //  Regardless of which <li> element is clicked, the pop-up value is Len, indicating that I is the same as the value for printing I after for.     };}

After using closures:

var aLi = document.getelementsbytagname (' li ');  for (var i=0, len=ali.length; i<len; i++) {  = (function(i) {    return  function() {      //  Click the <li> element at this point and the corresponding subscript will pop up. }   }) (i);}

Three, precautions
1. Memory leak
Because the closure causes variables in the function to be stored in memory, memory consumption is high , so can not abuse closures, otherwise it will cause Web page performance problems.
For example:

function Foo () {   var odiv = document.getElementById (' J_div ');    var id =  odiv.id;    function () {     //  alert (odiv.id), there is a circular reference here, Odiv is still in memory after the low version of IE page is closed. So try to cache the base type instead of the object.       alert (ID);   };    = null;}

2. Variable naming
If the variables of the intrinsic function and the variable name of the external function are the same, then the intrinsic function cannot point to the variable with the same name as the outer function.
Like what:

function foo (num) {  returnfunction(num) {    console.log (num);   }} var New foo (9//  undefined

In fact, the above usage, the jargon called function currying, is to transform a function that accepts multiple parameters into a function that takes a single parameter (the first parameter of the initial function) and returns a new function that accepts the remaining parameters and returns the result. In essence, the features that can be cached by closures are also used, such as:

varAdder =function(num) {return function(y) {returnnum+y; };};varinc = Adder (1);varDec = Adder (-1);//Inc, Dec is now two new functions that will pass in parameter values (+/‐) 1Alert (inc (99));// -Alert (Dec (101));// -Alert (Adder (100) (2));//102Alert (Adder (2) (100));//102

Again such as Ali Yuber's Seajs Source:

/**/function  istype (type  ) {returnfunction( obj) {    return {}.tostring.call (obj) = = "[Object" + Type + "]"  }}var IsObject = Istype ("Object"); var isstring = Istype ("String");

JavaScript closures Simple Comprehension

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.