Home > Web Front-end > JS Tutorial > body text

Detailed explanation of how Javascript closures work

零到壹度
Release: 2018-04-08 16:05:04
Original
1239 people have browsed it

The so-called closure is an expression (usually a function) that has many variables and an environment bound to these variables, so these variables are also part of the expression.

My understanding here is: In fact, all function methods in js can actually be counted as closures. In simple terms, they can also be understood as nested functions. Usage of the method:

For example, the following code example:

function run(){
   var a=10;
    return function(){
	a++;
	console.log(a);
    }
}
var foo=run();
foo();//11
foo();//12 
foo();//13
Copy after login

Analysis: The value of foo at this time is equal to run( ) The return value of the function, the foo function is a closure;

1) The execution process is to first call the foo() method. The foo() method will find the return function method in the run() method. This The return function method will point to the a variable in the run() method, and then when foo() is executed, 11 will be output;

2) In the above example, due to the existence of the closure, the function After run returns, a in run() always exists, so that every time foo() is executed, a will be the value of a after adding 1 to the console.

Related recommendations:

What is a closure

The most detailed explanation of closures

##In-depth understanding of js closures

The above is the detailed content of Detailed explanation of how Javascript closures work. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template