Closures in JavaScript

Source: Internet
Author: User

Closures:

Explanation in MDN: closures refer to functions that have access to independent (free) variables (variables are used locally but are defined in a closed scope). In other words, these functions can "remember" the environment when it was created.

The simple understanding is:

If a function retains a link to the parent scope after its parent function returns, the associated closure is created.

Closure # # #:

varA = "global variable";varF =function(){       varb = "local variable"; varN =function(){              varc = "Inner local"; returnb; }       returnN;}//The function n has its own private space and can access both the space of F () and the global space, so B is visible to it because F () is a global function, so it can be assigned the value of its return value to//other global variables that generate a new global function that can access the F () private space. varInner =F (); inner ();

Closure #:

F () no longer returns a new function, but creates a new global function inner () directly within the function body.

var Inner; var function () {       var b = "local variable";        var function () {              return  b;       };        = N;} // at this point, the F () function is called, and a new function n is created and assigned to the global variable inner.  F (); inner ();

Closure # # #:

The function returns a child function that returns the parameters of the complex function:

function F (param) {       varfunction() {              return  param;       }       Param++       ; return N;} var inner = F (ten); inner (); //  One

So we know that the function is bound to the scope itself, not the value returned by the variable in the scope when the function is defined.

Closures in the loop:

Consider a three-time loop operation that creates a new function in each iteration that returns the current sequence number, which is added to an array and returned.

functionF () {vararr =[],i;  for(i=0;i<3;i++) {Arr[i]=(function(x) {return function(){                            returnx;       }} (i)); }       returnarr;}vararr =F (); arr[0]();//or, if you do not use immediate functions, localize the value of I:functionF () {functionBinder (x) {return function(){                     returnx; }       }       vararr =[],i;  for(i=0;i<3;i++) {Arr[i]=Binder (i); }       returnarr;}

Applications for closures:

App # #:

To protect a private variable:

 var   Getvalue,setvalue; ( function   () { var        Secret = 0; GetValue  = function   () { return   secret;       }; SetValue  = function   (v) { if  (typeof  v = = = ' Number '               = V; }}} (); GetValue (); SetValue ( 11 // 11  

App # #: (iterator)

The next package is given to the easy-to-use next () function.

function Setup (x) {       var i = 0;        return function () {              return x[i++];       }} var next = Setup ([' A ', ' B ', ' C '); next ();" A "next ()" B "Next ()

Application #:

function Makesizer (size) {       returnfunction() {              = size + ' px ';       var size12 = Makesizer (n); var size14 = Makesizer (+); var size16 = Makesizer (+);d Ocument.getelementbyid (' size-12 '). onclick = size12; document.getElementById (' size-14 '). onclick = Size14;document.getelementbyid (' size-16 '). onclick = Size16;

Application # #:

(module mode, which uses closures to define public functions, and which can access private functions)

varCounter = (function(){       varPrivatecounter = 0; functionChangeby (val) {Privatecounter+=Val; }       return{increment:function() {Changeby (1); }, Decrement:function() {Changeby (-1); }, Value:function(){                     returnPrivatecounter; }}) (); Console.log (Counter.value ()); Counter.increment (); Counter.increment (); Console.log (Counter.value ()); Counter.decrement (); Console.log (Counter.value ()); 

Closures in JavaScript

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.