What is a closure? -Python tutorial

Source: Internet
Author: User
Tags chrome developer chrome developer tools
Php Chinese network (www.php.cn) provides the most comprehensive basic tutorial on programming technology, introducing HTML, CSS, Javascript, Python, Java, Ruby, C, PHP, basic knowledge of MySQL and other programming languages. At the same time, this site also provides a large number of online instances, through which you can better learn programming... Reply: The Nature of JavaScript closures comes from two points. lexical scopes and functions are passed as values.

The lexical scope means that, according to the code writing, internal functions can access variables outside the function. The engine uses data structures and algorithms to represent a function, allowing the engine to access peripheral variables according to the lexical scope rules during code interpretation and execution. these variables are registered in the corresponding data structure.

A function is passed as a value, that is, a first class object. A function can be assigned a value as a parameter to another function, or a return value. When a function is returned as a value, it is equivalent to returning a channel, which can access the variables in the function lexical scope, that is, the data structure required by the function is saved, the values in the data structure are created when the outer function is executed. the outer function is destroyed after execution, but these values are saved because the internal function is returned as values. And cannot be accessed directly. the returned function must be used. This is private.

The execution process and the lexical scope are closed. The Returned function is like a worm hole. That is, the meaning of the word "wheel brother" in the answer to "Autumn Moon.

Obviously, the formation of the closure is very simple. after the execution process is complete, the return function or the function can be preserved to form the closure. Closures are not very common in JavaScript code.

After functions are the first object, JavaScript is flexible. The closure is actually a very general concept, as @ Z said: "The closure is the common embodiment of lexical scopes and functions as First-class 」. Many familiar languages support functions as a class object, such as JavaScript, Ruby, Python, C #, Scala, java8 ....., all of these languages provide the closure feature, because the closure can greatly enhance the processing capability of the function, and the function can be used as a class of objects to make better use of this advantage.

What is a closure? to put it simply, a function holding external environment variables is a closure.

Understanding closures usually has the following key points:
1. Functions
2. free variables
3. environment

Example:

let a = 1let b = function(){    console.log(a)}
I recently paid special attention to reading some things about closures, for example, this
Concepts, forms, and applications of closures
I have probably understood such a thing and basically mastered the usage of this product, but I still have a vague understanding of the meaning of the closure until I see this @ vczh
I feel that most of the answers are too complicated, too theoretical, and so on, without grasping the essence and essence. Actually, closures are not that complex.

The simplest answer:

A Closure is a stateful (non-disappearing private data) function (object); or a Closure is a memory function.

The MDN is defined as follows:

Closures are FunctionsThat refer to independent (free) variables. In other words, the function defined in the closure 'remembers 'the environment in which it was created.

Closures-JavaScript

First, it is clear that a closure is a special function. What is a function? A function is a basic program running logic unit (module). Generally, there is a set of inputs, an output result, and some program statements for calculation. Therefore, it is wrong to say that the closure is a scope or something else, at least not accurate.

There is a more detailed explanation in MDN:

A closure is A special kind of objectThat combines two things: a function, and the environment in which that function was created. The environment consists of any local variables that were in-scope at the time that the closure was created.

The following is an example of the simplest JavaScript closure. inc is a closure (function/function) with a private data (state) count.

Var inc = (function () {// The statement in the function body will be immediately executed var count = 0; // return function () initialization of local variables () {// return an embedded closure function reference return + + count; // when the external function return, the count here is no longer a local variable of the external function. };}) (); Inc (); // count: 1inc (); // count: 2
The explanations for other answers are already very detailed. I will not write more about my understanding, but it seems that only text descriptions may not be easy for new people to understand. I will show my scum code, write four examples ~
Write four examples of understanding JS closures-Issue #8. AutumnsWind/Good-text-Share-GitHub
First:

Function love (name) {var text = 'hello' + name; var me = function () {console. log (text);} return me;} var loveme = love ('autumnswind'); loveme (); // output Hello AutumnsWind
A closure is a function that has the right to access the variables in another function scope.

The most common closure is to create another function within a function. For example:

function f(a) {    return function() {        return a;    }}
Easy to understand

A closure is generated when a function can remember and access its lexical scope, even if the function is executed outside the current lexical scope.

Common examples

1. Call functions in a function(The functions in the function can ensure that the external function scope will not be destroyed. Therefore, functions in the function or called outside can access the outer function scope, the specific method can be to use the function as the return value and then call it through two parentheses)

2. Callback function(The callback function retains the current outer scope and calls back to another place for execution. during execution, it is the closure)

3. IIFE mode(Strict calculation is not a closure, that is, the format of (function)

What is the use of closures?

In my opinion, because the closure can retain its lexical scope, you can use this scope externally to set and obtain the value of the scope variable through the closure ,, it can also pass external data to the scope for execution through parameters, A bit similar to the concept of class (maybe something wrong)

Loops and closures

Because JavaScript does not have block-level scope, the loop is the scope outside the loop. if the loop is written in the global, the closure in the loop retains the global scope, and there is only one global scope, therefore, the following code cannot output an additional number every second (5 or 6 consecutive times, variable I is a global variable, and the loop is executed very quickly, and I becomes 6 at once, therefore, the output is 6)

for (var i=1; i<=5; i++) { setTimeout( function timer() {  console.log( i ); }, i*1000 );}
Antesedent in Sequent ). No. js, so let's talk about the concept of closure.
It can be understood as follows:
Closure closed means that the environment is closed, and the computation in it will not depend on or involve anything other than the environment.
Therefore, the closure of a function is the smallest set of all external things that it may need, such as adding various dependent free variables. The pictures below are from https://gist.github.com/paulirish/4158604 This is an example of javascript closure illustrated in Chrome Developer Tools. I think it is very useful to post it.

Closure is a function that can access a field. it is no longer mysterious to compare this field with window.

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.