On javascript closures

Source: Internet
Author: User
Tags closure

First, background knowledge

Before I introduce closures, I think it is necessary to introduce some background knowledge, such as the scope of variables, nested functions, garbage collection mechanism and so on.

1. Scope

Scope is the scope of the program run time-varying amount can be accessed, the variable defined in the function is a local variable, the scope of the local variable can only be within the scope of the function, it cannot be referenced outside the function. the variable that defines the outermost of the module is a global variable, which is visible globally and, of course, can be read to global variables within the function.

var // Global Variables function Fun () {    var// local variable }

2. Nested functions

A function can be defined not only at the outermost layer of a module, but also within another function, such as a function defined inside a function called a "nested function". As shown below:

1 function foo () {2     function goo () {3         alert (123); 4     }5    goo (); 6 }

3. Garbage collection mechanism GC

JavaScript has an automatic garbage collection mechanism (Gc:garbage collecation), which means that the execution environment is responsible for managing the memory used during code execution. Principle: The garbage collector periodically (periodically) finds variables that are not in use and releases its memory.
When the GC reclaims memory, it first determines whether the object is referenced by another object. The memory area of the object is freed if no other object reference is determined.

Ii. What is closure closure

With regard to closures, the "official" explanation is that closures are an expression (usually a function) that has many variables and environments that bind them, and therefore these variables are also part of the expression. It is believed that very few people can read this sentence directly, because it describes too academic.

In fact, understanding the meaning of closures is not difficult. Next, I'll create a closure with JavaScript to help you understand what a closure is, because as a programmer, sometimes it's easier to see the code to understand a point of knowledge than you would see in a text definition.

function A () {    var foo = 123;     function B () {        alert (foo);    }     return B;} var c = A (); C ();

The above code is translated into natural language as follows:

(1) Defines a common function a
(2) A normal function B is defined in a
(3) return B in a (to be exact, a reference to B is returned in a)
(4) execute a () and assign the return value of a to the variable C
(5) Execute C ()

Summing up these five steps is: function A's internal function B is referenced by a variable C outside of function A;

I'll turn this sentence into a closure. The definition of closures: When an intrinsic function is referenced by a variable outside its external function, a closure is formed.

You can also say this: closures are functions that have access to variables in another function scope.

third, the role of closures

In fact, the difference between a closure and a normal function is that the local variable can still be accessed by the code outside the function after the function execution ends. This means that the function must return a reference to the closure, or assign the reference to an external variable to ensure that the local variables in the closure are accessed by external code. Of course, the entity that contains this reference should be an object, because in JavaScript the remainder of the basic type is the object.

in short, the function of a closure is that after a executes and returns, the closure makes the garbage collection mechanism of the JavaScript GC does not reclaim the resources used by a, because the execution of the internal function B of a requires a dependency on the variables in a.

So when we need to define a variable in a module that can be kept in memory without polluting the global, we can define the module with a closure.

Four, closure of the application scenario

1, the security of the variables within the protection function. For example, in the third example above, the function A can only be accessed by function B, and cannot be accessed by other means, thus protecting the security of F.

2. Maintain a variable in memory. As in the previous example, because of the closure, the Foo in function a always exists in memory, so each time C () is executed, a pop-up box with the content "123" will pop up.

The above two points are the most basic application scenarios for closures, and many of the classic cases originate from this.

why the closure will not be recycled by JS garbage collection mechanism

in JavaScript, if an object is no longer referenced, the object is garbage collected GC Reclamation. If two objects are referenced by each other and are no longer referenced by the 3rd, then the two mutually referenced objects are also recycled.

Take the third example above: Since function A is referenced by function B, function B is also referenced by the variable C outside of function A, which is why function A is not recycled after it is executed.

Vi. Summary

The above is a simple understanding of closures, in fact, about the closure of the knowledge point is far more than the above mentioned above, want to go deeper to understand the closure, back to the These concepts are the execution environment of JS (execution context), the active object (Activation object), and the operating mechanism of the scope (scope) and scope chain (scope chain). However, as a beginner, in fact, it is not necessary to understand these at the moment.

Of course, if you want to know more about closures, take a look at one of my other blogs, "deep understanding of javascript closures."

Reference: http://blog.csdn.net/hitman9099/article/details/3854171

On javascript closures

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.