Get the App
SLTechnology News&Howtos  ›  Development  › 

What is the implementation principle of closure in JavaScript?

Shulou Source: shulou.com Published: 2022-06-01 03:46:05 09月16日 Update

This article will explain in detail what is the implementation principle of closures in JavaScript. The editor thinks it is very practical, so I share it with you as a reference. I hope you can get something after reading this article.

What is a closure and why use it?

A closure is a function that has access to variables in the scope of another function. the most common way to create a closure is to create another function within a function that can access the local variables of the current function.

Closures have two common uses.

The first use of closures is to enable us to access variables inside the function outside the function. By using closures, we can access variables inside the function externally by calling the closure function externally, and we can use this method to create private variables.

Another use of the function is to keep the variable object in the context of the function that has been run out of memory, because the closure function retains a reference to the variable object, so the variable object is not recycled.

Function a () {var n = 0; function add () {nkeeper; console.log (n);} return add;} var A1 = a (); / / Note that the function name is only an identification (a pointer to the function), and () is the executing function; A1 (); / / 1a1 (); / / 2 the second call n variable is still in memory

In fact, the essence of closure is a special application of domain chain. As long as we understand the process of creating domain chain, we can understand the implementation principle of closure.

This is the end of this article on "what is the principle of closures in JavaScript". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, please share it out for more people to see.

Tags: Functions closures variables principles functions objects uses articles memory that is more not bad practical special below two content but can pass local Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Redmi Huawei vpn Linux macOS