JavaScript closures and their solutions

Source: Internet
Author: User
Tags closure

Closed Package

is to declare a function in a function that returns a reference to an intrinsic function at the end of the external function, and then when the external function is executed

Generates a reference to an intrinsic function, because the external function is executed, and the reference to the AO of the external function should be deleted or released.

But because of the reference to the intrinsic function, this intrinsic function points to the AO and go of the external function at the time of declaration, so even if the external function

The reference to AO has been released, since the intrinsic function is saved externally, resulting in the outer function declaration and execution resulting from the AO being preserved.

<body> <script type= "text/javascript" > function  A () {  function B() {         var bbb = 234;      Consloet.log (AAA); };
var a = 123 return b;    } var = Golb;     var demo = A (); Demo (); </script></body>

The output of this example is: 123

According to the original understanding, there is no variable a in the B function, normal if there is no external a function, it will be an error define

But here, because at the end of a execution, the reference to B is stored outside function A, and B, when declared, its scope chain is still the same as a execution,

That is: 0:aao;1:go, the execution context in a is saved in the B function. When the function B is executed, it becomes a bao placed in the 0 position of the scope chain, executed

Time to delete this Bao, while in the 1, 2 position 0:aao;1:go is permanently preserved.

AAO is the variable of a = 123, so the final result is to print out the value of a! ~

This is the closure!

* * NOTE * *------When the intrinsic function is saved externally, a closure is generated. Closures can cause the original scope chain (scope chain) not to be released, causing a memory leak

Memory leaks: Because memory is occupied, resulting in reduced available memory, it feels like a memory leak, called a memory leak ~~! Will cause the load to be very slow!!

In scope chain, a new AO is not generated, it is necessary to inherit the AO and go generated by the external function, where the inheritance refers to the original AO, go, instead of creating an identical

Ex

<body> <script type= "Text/javascript" > function text () {var num = +;                  Function B () {                       num + +;                       Console.log (num);                      }                 Function B () {                      num--;                      Console.log (num);                 }                  return [A, b];    } var Myarr = text ();    Myarr[0] (); MYARR[1] ();</script></body>                                                       

The result of the output is: 101 100

Instead of 101 99, pay attention to the difference!

So when you modify the AO from an external function, it is the same AO that was modified

Ex

<body> <script type= "Text/javascript" > Function A () {var num = +;                  Function B () {                       num + +;                       Console.log (num);                      }                  return b;    } var demo = a ();    Demo (); Demo ();</script></body>                        

The result of this example is: 101

102

Have a cumulative effect

closure function : 1 Implement common variable-----> function accumulator

2 can do cache (storage structure)----->eater

3 can implement encapsulation, property privatization------>person ();

4 modular development to prevent contamination of global variables

Ex: Implementing common variables-----> function Accumulator

<body> <script type= "Text/javascript" > Function Add () {  var count = 0;                        Function Demo () {count + +;      Consloet.log (count);             };    return demo;        } var counter = Add (); Counter ();            Counter ();               Counter ();               Counter ();               Counter ();               Counter ();               Counter ();               Counter ();   </script></body>                 

Output results: 1 2 3 4 5 6 7

Ex: can do cache (storage structure)----->eater 3

<body> <script type= "Text/javascript" > Function Eater () {var food = "";                  var obj = {                        eat:function () {                        Console.log ("I am eating!" + food);                        Food = "";                        },                        push:function (myfood) {Food                                = Myfood;                        }                  }                  return obj;              }      var demo = a ();      erter1.push (' banana ');  eater1.eat ();</script></body>         

output; I am eating banana

There are actually two processes, one put banana into myfood, the second process is to print I am eating banana

JavaScript closures and their solutions

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.