首頁  >  文章  >  web前端  >  JavaScript 中的閉包

JavaScript 中的閉包

WBOY
WBOY原創
2024-09-12 10:30:02910瀏覽

Closures in JavaScript

Hi there,

In this post, Let's learn Closures.

Closures are essential in JavaScript because they allow a function to access variables from its parent scope, even after that parent function has closed. This is crucial for functions that need to remember data over time, like in callback functions or maintaining state. One point to remember here is the unused variables of parent scope are garbage collected.

Definition:
A closure is the combination of a function bundled together (enclosed) with references to its surrounding state (the lexical environment). In other words, a closure gives a function access to its outer scope. In JavaScript, closures are created every time a function is created, at function creation time.

Basically closures have access to:

  • Their own scope
  • The scope of the outer functions
  • The global scope

Bonus Point
Lexical Scope : Inner functions have access to variables in outer scope.

Let's understand with example.

Example

Q> Write a function createCounter. It should accept an initial integer init. It should return an object with three functions.

The three functions are:

increment() increases the current value by 1 and then returns it.
decrement() reduces the current value by 1 and then returns it.
reset() sets the current value to init and then returns it.

See the commented code below for init = 5 case example.

Solution

var createCounter = function(init) {
    const INITIAL_VALUE = init;
    return {
        increment: () => ++init,
        decrement: () => --init,
        reset: () => init=INITIAL_VALUE,
    }
};

/**
 * const counter = createCounter(5)
 * counter.increment(); // 6
 * counter.reset(); // 5
 * counter.decrement(); // 4
 */

Explanation:

  • Capturing the init variable in its lexical scope.
  • Returning methods that can access and modify init even after createCounter finishes executing.
  • Creating a private, persistent state (init) that's accessible only through the returned methods.
  • Allowing creation of multiple independent counters, each with its own encapsulated state.

If you have any doubts or suggestions feel free to add in comments.

This question was taken from leetcode. Link

Lastly keep in mind that globally declared variables will be accessible to every closure in a script.

I hope now you have a good understanding of closures. Thank you for reading

以上是JavaScript 中的閉包的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn