Home > Web Front-end > JS Tutorial > Closures in JavaScript_javascript tips

Closures in JavaScript_javascript tips

WBOY
Release: 2016-05-16 15:13:52
Original
1229 people have browsed it

1. What is closure

Closure, the official explanation of 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.

Simply put, Javascript allows the use of internal functions---that is, function definitions and function expressions are located in the function body of another function. Furthermore, these inner functions have access to all local variables, parameters, and other inner functions declared in the outer function in which they exist. A closure is formed when one of these inner functions is called outside the outer function that contains them.

Characteristics of closures

1 function nested function

2 External parameters and variables can be referenced inside the function

3 Parameters and variables will not be recycled by the garbage collection mechanism

After the general function is executed, the local active object is destroyed, and only the global scope is saved in the memory. But the situation with closures is different!

function fn(){
var a = ;
function fn(){
//可以访问fn中定义的a值
alert( a++ );
}
fn();
}
fn(); //
fn(); // 
function fn(){
var a = ;
function fn(){
//可以访问fn中定义的a值
  alert( a++ );
}
return fn;//
}
var f = fn();
f(); // 执行完后a还在内存中
f(); //
f = null; //a被回收
Copy after login

The above is the editor’s introduction to closures in JavaScript. I hope it will be helpful to you!

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