Learn JavaScript closures (Closure) __java

Source: Internet
Author: User
Tags closure garbage collection variable scope

Closures (closure) are a difficult and unique feature of the JavaScript language, and many advanced applications rely on closure implementations.

Another understanding of closures (closure):

First of all, I think that a concept, if not understand also does not affect the use of words, then, there is no need to understand it, to learn it. Closures are such a concept that you can use it well without understanding it. I wrote the AS3 program in the past two years, is to deal with it every day, even have a function set one, a method of more than 20 function in the extreme example, but never delve into how it is achieved, it is like water and air, we do not need to know that water is H2O, Air is the mixture of oxygen, nitrogen, carbon dioxide and so on, and live well.

Secondly, I think that the online interpretation of the concept of closure is too narrow, watching people's eggs pain, like back to the i++,++i era. If you want to understand the concept, like that to understand, the harvest is too small, not worth it.

Wikipedia has a classic explanation for closures:

In computer science, closures (Closure) are abbreviations for lexical closures (lexical Closure), which are functions that refer to free variables. The referenced free variable will exist with this function, even if it has left the environment that created it. So, there is another saying that closures are entities that are combined by functions and reference environments associated with them.

In 1964, Peter J. Landin defined the term closure as an entity containing environmental components and control components.

Here is the concept of closure that I understand.

Let's look at the math closures first.

(1,5) is an interval, but for this interval to do analysis, calculate what, often used to 1 and 5 of these two values do not belong to this interval, [1,5] is (1,5) closure.

In life, we do things, find a department, a department said, you have to find B Department cover a chapter, B department said, you first have to find C Department cover a chapter, C department said, this thing is not our terms of reference ... Buck, this is the non-closure package. Closure is responsible for the end, you find a department, a department reception of the person responsible for the end, he/she to coordinate B Department and C department.

In engineering, closures are the project manager, which is responsible for scheduling the resources needed for the project. Boss, customers have anything, directly to the project manager can, no longer to find other people.

In the programming language, the closure is a kind of grammatical sugar, it is in the natural form, our purpose and our purpose of the resources involved are automatically packaged together, in a natural, as far as possible not to be misunderstood way to let people use. As for its specific implementation, my personal opinion, without affecting the use of the case, superficial understanding can be. In many cases, it is necessary to access the external local variables in a section of code, do not provide this syntax sugar, you need to write a lot of code, with the syntax of the closure of the sugar, there is no need to write so much code, naturally used.

In this way, the closure can be promoted from a grammatical mechanism to a design principle:

Closure is a design concept from the user's point of view, based on the analysis of the context, the dirty things, complex things and the external environment to interact with the things they have done, leaving the user a very natural interface.

Under this principle, in a functional language, the so-called closure is just a "closure", and there are a number of other types of "closures" waiting to be discovered and implemented.

Here are some examples of closure design principles and their counter examples.

Positive example:

The data binding syntax in Flex is a "closure." x= "{b.num + c.num}", for this syntax, the compiler automatically searches the context for variables called B and C, and then looks for their internal num variables and, if they are all bindable, automatically adds a binding chain to them, updating the value of x when B, C, NUM, and so on have any change.

scope of a variable

To understand closures, you must first understand JavaScript's special variable scope.

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.

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

second, 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 the F2 as long as the return value.

Function F1 () {

var n=999;

function F2 () {
alert (n);
}

return F2;

}

var result=f1 ();

Result (); 999

third, the concept of closure

The F2 function in the previous section of the code is the closure.

The definition of "closure" (closure) in various professional literature is very abstract and difficult to read. My understanding is that closures are functions that can read internal variables of other functions.

Because in a JavaScript language, only a child function within a function can read a local variable, the closure can be simply understood as "a function defined within a function."

So, in essence, closures are a bridge that connects functions inside and outside functions.

Iv. use of closures

Closures can be used in many places. Its maximum use is two, one is the previous mentioned can read the function inside the variable, the other is to keep the values of these variables always in memory.

How to understand this sentence. Take a look at the code below.

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 so? 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.

Five, 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.

VI. Study Questions

If you can understand the results of the following two sections of code, you should understand the operation mechanism of the closure.

Code fragment one.

var name = "the window";

var object = {
Name: "My Object",

Getnamefunc:function () {
return function () {
return this.name;
};

}

};

Alert (Object.getnamefunc () ());


Code fragment two.

var name = "the window";

var object = {
Name: "My Object",

Getnamefunc:function () {
var that = this;
return function () {
return that.name;
};

}

};

Alert (Object.getnamefunc () ());

Summarize:

(1) Closure is a design principle, which simplifies the user's invocation by analyzing the context, so that the user can achieve his goal without knowing it;

(2) The online mainstream analysis of the closure of the article is actually and the closure principle of the reverse, if you need to know the closure details can be used well, this closure is the design failure;

(3) From the technical understanding, closure is a thief, get the original should not get things (other people's functions), from the design mode of understanding is the façade mode

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.