Closures in JavaScript

  • 2021-01-03 20:48:09
  • OfStack

1. What is a closure

A closure, the official interpretation of a closure is that an expression (usually a function) has a number of variables and the environment to which these variables are bound, and therefore these variables are also part 1 of the expression.

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

The characteristics of closures

1 Functions nested functions

Functions can refer to external parameters and variables internally

3 Parameters and variables are not collected by the garbage collection mechanism

After the execution of the general function, the local active object is destroyed, and only the global scope is kept in memory. But closures are different!


function fn(){
var a = ;
function fn(){
// You can visit fn Defined in the a value 
alert( a++ );
}
fn();
}
fn(); //
fn(); // 
function fn(){
var a = ;
function fn(){
// You can visit fn Defined in the a value 
  alert( a++ );
}
return fn;//
}
var f = fn();
f(); //  After the execution a It's still in memory 
f(); //
f = null; //a Be recycled 

This is a helpful introduction to closures in JavaScript!


Related articles: