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

A brief discussion on closures in JS_Basic knowledge

WBOY
Release: 2016-05-16 17:24:41
Original
1006 people have browsed it

( ⊙o⊙ )! ! ! This is too official. As a newbie, I can’t understand what it means! But as a curious newbie, I really want to know what "closure" is! So I finally found the legendary "Du Niang" to help! I still have a little understanding!

Personal opinion: Define another method function in the function body, and this method function is referenced by variables outside the function, then a closure is formed!

Maybe this understanding is too abstract and not so simple and easy to understand! Example:

Copy code The code is as follows:


The above code creates a closure, because when the function is executed to var C=A();, it seems that C points to function A, but in fact the function pointed to by C is function B. So when C() is executed, 2 will be output; in this case, function B is referenced by variables other than function A. Based on personal opinion, a closure is created!

When I learned about closures in a small way, I also looked at the uses of closures. It is said that there are two main uses of closures:

1. You can read the variables inside the function

2. Keep these variables in memory at all times

Copy code The code is as follows:



In the above code, C still points to function B. C is executed twice, and the first time it is output 1. The second output is 2, which proves that S has been saved in the memory and is not automatically cleared after the A function is called. Why is this? The reason is because the B function is assigned to a global variable. This As a result, function B has always been in memory, and the execution of function B needs to depend on function A, so A has always been in memory and will not be recycled after the call is completed! (This understanding seems a bit unprofessional)!

The expression is completed, please give us your advice!

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