Two examples of JavaScript closures

Source: Internet
Author: User
Tags anonymous closure garbage collection


Characteristics of closures

Closures have three features:

1. Function Nesting function
2. Functions can refer to external parameters and variables inside
3. Parameters and variables will not be recycled by garbage collection mechanism
Definition of closure and its advantages and disadvantages

Closures are functions that have access to variables in the scope of another function, and the most common way to create closures is to create another function within one function and access the local variables of the function through another function.

The advantage of using closures is that it is also a disadvantage that local variables can reside in memory, avoiding the use of global variables. Global variables can be invoked in every module, which is bound to be disastrous. (So it is recommended that you use private, encapsulated local variables.) )

After the normal function is finished, the local active object is destroyed and only the global scope is saved in memory. But the closures are different!

Closure of nested functions

function aaa () {
var a = 1;
return function () {
Alert (a++)
};
}
var fun = aaa ();
Fun ()//1 a++ after execution, and then A is still in ~
Fun ();//2
Fun = null;//a is recycled!!
Closures cause variables to always be stored in memory, which can increase memory consumption if improperly used.

The principle of garbage collection in JavaScript

(1), in JavaScript, if an object is no longer referenced, then the object will be collected by GC;
(2) If two objects are referenced to each other and are no longer referenced by the 3rd, then the two referenced objects are also reclaimed.

Benefits of using closures

So what's the benefit of using closures? The benefits of using closures are:

1. Want a variable to be stationed in memory for a long time
2. Avoid pollution of global variables
3. Existence of Private members

The summation of global variables

<script>
var a = 1;
Function abc () {
a++;
alert (a);
}
ABC (); 2
ABC (); 3
</script>

Second, local variables

<script>

Function abc () {
var a = 1;
a++;
alert (a);
}
ABC (); 2
ABC (); 2
</script>

So how do you make variable a both local and additive?

The summation of local variables

<script>
function outer () {
var x=10;
return function () {//functions nested functions
x + +;
alert (x);
}
}
var y = outer (); The external function is assigned to the variable y;
Y (); The Y function is called once, and the result is 11, equivalent to outer () ();
Y (); The Y function calls the second time, and the result is 12, which realizes the cumulative
</script>

function declarations and function expressions

In JS we can declare a function by using the keyword function:

<script>
Function abc () {
alert (123);
}
ABC ();
</script>

We can also use a "()" to turn this declaration into an expression:

<script>
(function () {
alert (123);
})(); You can then call the preceding expression directly by (), so the function does not have to write a name;
</script>

Four, modular code to reduce the global variable pollution

<script>
var abc = (function () {//ABC is the return value of an external anonymous function
var a = 1;
return function () {
a++;
alert (a);
}
})();
ABC (); 2; Calling an ABC function is actually the return value of the internal function inside the call
ABC (); 3
</script>


V. Existence of PRIVATE members

<script>
var AAA = (function () {
var a = 1;
function bbb () {
a++;
alert (a);
}
function CCC () {
a++;
alert (a);
}
return {
B:BBB,//json structure
C:ccc
}
})();
AAA.B (); 2
AAA.C ()//3
</script>


Six. Using anonymous functions to achieve the cumulative

Using anonymous functions to implement local variables to reside in memory, which enables cumulative

<script type= "Text/javascript" >

 function box () {
     var age = +
     return function () {& nbsp;        //anonymous function
           age++;
          return age;
    };

}
var b = box ();
Alert (b ());
Alert (b ()); That is, alert (box () ());
Alert (b ());
alert (b); function () {
age++;
return age;
//       }

b = null;//dereference, waiting for garbage collection
</script>


Excessive use of closures can lead to performance degradation. function, the closure is generated.

Find the index of the corresponding element directly in the loop

<! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en"
"Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd" >
<meta http-equiv= "Content-type" content= "Text/html;charset=utf-8"/>
<title></title>
<script>
Window.onload = function () {
var aLi = document.getelementsbytagname (' li ');
for (Var i=0;i<ali.length;i++) {
Ali[i].onclick = function () {//When clicked for loop is over
alert (i);
};
}
}
</script>

<body>
<ul>
<li>123</li>
<li>456</li>
<li>789</li>
<li>010</li>
</ul>
</body>


Use closure to rewrite the above code

<! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en"
"Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd" >

<meta http-equiv= "Content-type" content= "Text/html;charset=utf-8"/>
<title></title>
<script>
Window.onload = function () {
var aLi = document.getelementsbytagname (' li ');
for (Var i=0;i<ali.length;i++) {
(function (i) {
Ali[i].onclick = function () {
alert (i);
};
}) (i);
}
};
</script>

<body>
<ul>
<li>123</li>
<li>456</li>
<li>789</li>
</ul>
</body>


Nine. Memory leak problem

Because IE's JS objects and Dom objects use different garbage collection methods, closures in IE can lead to memory leaks, which means that the elements residing in memory cannot be destroyed.

function Closure () {
var odiv = document.getElementById (' Odiv '), which resides in memory after the//ODIV has been exhausted
Odiv.onclick = function () {
Alert (' odiv.innerhtml ');//This causes memory leaks with Odiv
};
}
Closure ();

Finally, you should odiv the reference to avoid memory leaks
function Closure () {
var odiv = document.getElementById (' Odiv ');
var test = odiv.innerhtml;
Odiv.onclick = function () {
alert (test);
};
Odiv = null;
}

10. Study Questions

If you can understand the operating results of the following code, you should understand the closure mechanism.

 

<script type= "Text/javascript" >
var name = "TRIGKIT4";
var Segmentfault = {
Name: "My SF",
Getnamefunc:function () {
return function () {
return this.name;
};
}
};
Alert (Segmentfault.getnamefunc () ()); Pop-up TRIGKIT4
</script>


Further understand the scope and characteristics of JS closures.

var foo = (function () {
var secret = ' secret ';
Functions within the closure can access the secret variable, while the secret variable is hidden from the outside
return {
Get_secret:function () {
Access to secret through defined interfaces
Return secret;
},
New_secret:function (New_secret) {
Modify the secret by defining the interface
Secret = New_secret;
}
};
} () );

Foo.get_secret (); Get ' secret '
Foo.secret; Type error, Access cannot be
Foo.new_secret (' A new secret '); Through the function interface, we have accessed and modified the secret variable
Foo.get_secret (); Get ' a new secret '

It is possible to implement public, private, and privileged variables in JavaScript in this way because closures, which are meant to be in JavaScript, the intrinsic function can always access the arguments and variables declared in its external function, even after its external function is returned (the end of life).


var Foo = function () {
var name = ' Fooname ';
var age = 12;
This.getname = function () {
return name;
};
This.getage = function () {
return age;
};
};
var foo = new Foo ();

Foo.name; => undefined
Foo.age; => undefined
Foo.getname (); => ' Fooname '
Foo.getage (); => 12

The point to note is that the internal function accesses the internal variable itself, not its copy. So be careful when adding loop to the closure function. In addition, the closures feature can also be used to create private functions or methods.

Closures are a very important feature of JavaScript, which means that current scopes always have access to variables in external scopes. Because a function is the only structure in JavaScript that has its own scope, the creation of closures depends on the function.

One more:


<script type= "Text/javascript" >
var name = "TRIGKIT4";
var Segmentfault = {
Name: "My SF",
Getnamefunc:function () {
return function () {
return this.name;
};
}
};
Alert (Segmentfault.getnamefunc () ()); Pop-up TRIGKIT4
</script>
For more understanding of JS closures, or in the actual use of JS closure to solve the problem, so as to understand the depth of JS and ordinary JS functions of the difference.

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.