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

Is an inner function always a closure in JavaScript?

DDD
Release: 2024-10-31 08:03:01
Original
561 people have browsed it

Is an inner function always a closure in JavaScript?

JavaScript Closures vs. Anonymous Functions

In JavaScript, a closure occurs when an inner function has access to the outer scope's variables, even after the outer function has completed execution. Many functions in JavaScript are considered closures, but only a specific subset is of particular interest theoretically.

Case 1: Friend's Code

<code class="js">(function f() {
  var i2 = i;
  setTimeout(function g() {
    console.log(i2);
  }, 1000);
})();</code>
Copy after login
  • Function f is not a closure because none of its free variables are closed over. However,
  • Function g is a closure for the free variable i2. The variable i2 is captured when g is created.

Case 2: Your Code

<code class="js">setTimeout((function f(i2) {
  return function g() {
    console.log(i2);
  };
})(i), 1000);</code>
Copy after login
  • Function f is not a closure because it has no free variables.
  • Function g is a closure for the free variable i2. The variable i2 is captured when g is created.

Conclusion

Therefore, in both the provided solutions, the inner function g is a closure, but not the outer ones. This demonstrates that although they achieve the same result, they do so through different mechanisms.

The above is the detailed content of Is an inner function always a closure in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!