Home  >  Article  >  Web Front-end  >  When does javascript form a closure?

When does javascript form a closure?

WBOY
WBOYOriginal
2022-03-02 16:42:462164browse

In JavaScript, when an internal function is called outside the external function that contains the internal function, a closure is formed; a closure is a stack area that does not release resources when the function returns. , the closure serves as a reference to a function variable and is activated when the function returns.

When does javascript form a closure?

The operating environment of this tutorial: Windows 10 system, JavaScript version 1.8.5, Dell G3 computer.

When does JavaScript form a 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.

Characteristics of closure:

1. As a reference to a function variable, it is activated when the function returns.

2. A closure is a stack area that does not release resources when a function returns.

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.

function closure(){
var str = "I'm a part variable.";
return function(){
alert(str);
}
}
var fObj = closure();
fObj();

In the above code, str is a local variable defined in the function closure. If str can no longer be accessed after the closure function call is completed, str will be released after the function execution is completed.

But because the function closure returns an internal function, and the returned function refers to the str variable, str may be referenced after the closure function is executed, so the resources occupied by str will not Be recycled. This closure forms a closure.

Related recommendations: javascript learning tutorial

The above is the detailed content of When does javascript form a closure?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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