JavaScript – Closure Explained

JavaScript

Deprecated: get_the_author_email is deprecated since version 2.8.0! Use get_the_author_meta('email') instead. in /home/cloudber/public_html/wp-includes/functions.php on line 4713

1. A function inside another function, a closure is used.

2. A closure in JavaScript is like keeping a copy of all the local variables, just as they were when a function exited.

3. It is probably best to think that a closure is always created just an entry to a function, and the local variables are added to that closure.

4. A new set of local variables is kept every time a function with a closure is called (given that the function contains a function declaration inside it, and a reference to that inside function is either returned or an external reference is kept for it in some way).

5. Two functions might look like they have the same source text, but have completely different behaviour because of their ‘hidden’ closure. I don’t think JavaScript code can actually find out
if a function reference has a closure or not.

6. If you are trying to do any dynamic source code modifications (for example: myFunction = Function(myFunction.toString().replace(/Hello/,’Hola’));), it won’t work if myFunction is a closure (of course, you would never even think of doing source code string substitution at runtime, but…).

7. It is possible to get function declarations within function declarations within functions — and you can get closures at more than one level.

8. I think normally a closure is the term for both the function along with the variables that are captured. Note that I do not use that definition in this article!

Author: Wu Chia Chong

My main areas of interest are software architectures and software design methods, patterns, and new trends in software development.

Author: Wu Chia Chong

My main areas of interest are software architectures and software design methods, patterns, and new trends in software development.