The writing and function of closure in JavaScript _javascript skills

Source: Internet
Author: User
Tags closure garbage collection

1, what is closure

Closures are functions that have access to variables that are scoped to another function.
Simply put, JavaScript allows the use of intrinsic functions---i.e. function definitions and function expressions in the function body of another function. Furthermore, these internal functions can access all the local variables, arguments, and other internal functions declared in the external function in which they are located. A closure is formed when one of these intrinsic functions is called outside the external function that contains them.

2, the scope of the variable

To understand closures, you first need to understand the scope of variables.
The scope of a variable is nothing more than two kinds: global and local variables.

The special point of the JavaScript language is that the global variable can be read directly from within the function.

The internal function can access the variables of external functions, because the scope of the internal function chain contains the scope of external functions;

It can also be understood that the function range of the internal function radiates to the scope of the external function;

var n=999;
Function F1 () {
alert (n);
}
F1 (); 999

On the other hand, local variables within a function cannot naturally be read outside the function.

Function F1 () {
var n=999;
}
alert (n); Error

Here's a place to be aware that when declaring variables inside a function, you must use the var command. If not, you actually declare a global variable!

Function F1 () {
n=999;
}
F1 ();
alert (n); 999

3, the closure of several types of writing and usage

3.1. Add some attributes to the function

function Circle (r) { 
THIS.R = R; 
} 
Circle.pi = 3.14159; 
Circle.prototype.area = function () {return 
Circle.pi * THIS.R * THIS.R; 
} 
var c = new Circle (1.0); 
Alert (C.area ()); 3.14159

3.2. Declare a variable, assign a function as a value to a variable

var Circle = function () { 
var obj = new Object (); 
Obj. PI = 3.14159; 

Obj.area = function (r) {return this 
. PI * R * r; 
} 
return obj; 
} 
var c = new Circle (); 
Alert (C.area (1.0)); 3.14159

3.3, this method uses more, also the most convenient. var obj = {} is declaring an empty object

var circle={ 
"PI": 3.14159, 
' area ': function (r) {return this 
. PI * R * r; 
} 
}; 
Alert (Circle.area (1.0));//3.14159

4, closure of the main role

Closures can be used in many places. Its maximum usefulness is two: one is the previously mentioned variables that can read the inside of a function, and the other is to keep the values of those variables in memory.

4.1. How to read local variables from the outside?

For a variety of reasons, we sometimes need to get local variables within a function. However, as mentioned earlier, this is not possible under normal circumstances and can only be achieved by workaround.

That is, in the interior of the function, define a function.

Function F1 () {
var n=999;
function F2 () {
alert (n);//999
}
}

In the above code, the function F2 is included within the function F1, when all local variables within F1 are visible to F2. But the reverse is not, F2 internal variables, the F1 is not visible. This is the "chain scoped" structure (chain scope) peculiar to the JavaScript language, where child objects look up the variables of all the parent objects at one level. Therefore, all the variables of the parent object are visible to the child, and the opposite is not true.

Since F2 can read local variables in F1, we can not read the internal variables of F2 as long as the return value of the F1!

Function F1 () {
var n=999;
function F2 () {
alert (n); 
return
F2;
}
var result=f1 ();
Result (); 999

4.2. How do I keep the value of a variable in memory at all times?

Function F1 () {
var n=999;
Nadd=function () {n+=1}
function F2 () {
alert (n);
return
F2;
}
var result=f1 ();
Result (); 999
nadd ();
Result (); 1000

In this piece of code, result is actually the closure F2 function. It runs two times, the first value is 999, and the second value is 1000. This proves that the local variable n in the function F1 is kept in memory and is not automatically purged after the F1 call.

Why is that? The reason is that F1 is the parent function of F2, and F2 is assigned to a global variable, which causes F2 to always be in memory, and the presence of F2 depends on F1, so F1 is always in memory and will not be reclaimed by the garbage collection mechanism (garbage collection) after the call has ended.

Another notable part of this code is the "Nadd=function () {n+=1}" line, which first nadd not use the var keyword, so nadd is a global variable, not a local variable. Second, the value of Nadd is an anonymous function (anonymous functions), and the anonymous function itself is a closure, so the nadd is equivalent to a setter that can manipulate local variables within the function outside of the function.

5. Closures and this object

Using this object in closures can cause problems. Because the execution of an anonymous function is global, its this object usually points to window. The code is as follows:

var name = "The window";
var object = {
name: ' My object ',
getnamefun:function () {return
function () {return
this.name;}
;
}
};
Alert (Object.getnamefun () {}); "The Window" (in non-strict mode)

The This object in the external scope is saved in a variable that can be accessed by a closure, and it can be accessed by the closure. The code is as follows:

var name = "The window";
var object = {
name: ' My object ',
getnamefun:function () {
var = this;
return function () {return
that.name;
};}}; Alert (Object.getnamefun () {}); "My Object"

6, Closures and memory leaks

Specifically, if an HTML element is stored in the scope of the closure, it means that the element cannot be destroyed. As follows:

function Assignhandler () {
var element = document.getElementById ("someelement");
Element.onclick = function () {
alert (element.id);
}
}

The above code creates a closure that acts as an event handler for element elements, and the closure creates a circular reference. Because the anonymous function holds a reference to the active object of Assignhandler (), it causes an inability to reduce the number of references to the element. As long as the anonymous function exists, the number of references to the element is at least 1, so that the memory he occupies will not be reclaimed.

To resolve an internal problem that cannot be recycled by rewriting the code:

function Assignhandler () {
var element = document.getElementById ("someelement");
var id = element.id;
Element.onclick = function () {
alert (ID);
}
element = null;
}

The above code, the implementation of the closure does not directly refer to the element, contains the function of the active object will still save a reference. Therefore, it is necessary to set the variables of the element to null so that the memory they occupy can be recycled properly.

7, use the closure of the attention point

1 because the closure will make the function of the variables are stored in memory, memory consumption is very large, so can not abuse the closure, otherwise it will cause Web page performance problems, in IE may lead to memory leaks. The workaround is to remove all unused local variables before exiting the function.

2 The closure will change the value of the inner variable of the parent function outside the parent function. So, if you use the parent function as an object, using the closure as its common method, and the internal variable as its private property (private value), be careful not to arbitrarily change the value of the internal variable of the parent function.

The above is a small set of JavaScript to introduce the closure of the writing and the role of the explanation, I hope to help you, if you have any questions please give me a message, small series will promptly reply to everyone. Here also thank you very much for the cloud Habitat Community website support!

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.