Closure is a major feature of JS, but also a major difficulty. Simply put, a closure means that a function can access variables in the outer scope of its function.
The three main features of closures are:
1. Function Nesting function
2. Internal functions can access variables of external functions
3, parameters and variables will not be recycled.
For example:
- function Test () {
- var a=1;
- return function () {
- alert (a);
- }
- }
- var try=test ();
- try (); //Eject the value of a
In this example, the variable A is inaccessible outside of the test method, but inside the test method, an anonymous function is nested, returned by return, variable A in the test scope,
Can be accessed in anonymous functions. And when the test method executes, the memory that the variable a occupies does not release, to achieve the purpose that the nested function can also be accessed.
The function of closures is that private variables and methods can be designed by closing the packet.
For example: Create a Perosn class in Java that contains the private variable name.
- public class person{
- private String name=' WY ';
- Public person (val) {
- Name=val;
- }
- Public void setName(val) {
- Name=val;
- }
- Public String getName() {
- return name;
- }
- }
The ability to create a class similar to Java is implemented in JS:
- (function () {
- var name="Wangyu";
- person=function (val) {
- Name=val;
- }
- Person.prototype.setname=function (val) {
- Name=val;
- }
- Person.prototype.getname=Function () {
- return name;
- }
- })();
- var person1=new Person ("SJ");
- Alert (this.name)//undefined because it cannot be accessed outside the function domain
- Alert (Person1.getname ()); //wangyu
The name inside the function is not accessible externally because it is in the function scope, but can be achieved by creating a person object, calling the person's method.
The purpose of modifying and accessing the name value is similar to a private variable in a Java class that cannot be accessed externally and can only be accessed through a class method.
Let's look at an example of a private variable:
- var aaa = (function () {
- var a = 1;
- function bbb () {
- a++;
- alert (a);
- }
- function CCC () {
- a++;
- alert (a);
- }
- return {
- b:bbb, //json structure
- C:ccc
- }
- })();
- Alert (AAA.A)//undefined
- AAA.B (); //2
- AAA.C () //3
Summarize:
1. Closures are functions that have access to variables in another function scope, 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 disadvantage of closures is that resident memory increases memory usage and is prone to memory leaks if used improperly.
2, do not have to struggle in the end how to calculate the closure, in fact, you write every function counts as closures, even if the global function, you access the function outside the global variables, is the embodiment of the closure.
JS Closed Packet Understanding