What are JavaScript Closures: A Best Practices Guide

Closure refers to creating another function inside a function, and the inner function can access the variables, parameters and other inner functions of the outer function, even if the outer function has been executed. This mechanism enables inner functions to retain a reference to the outer scope, even if the outer scope is no longer active.

Why are closures important?

Closures   have important use and value in JavaScript . They can be used to create private variables, encapsulate logic, avoid global pollution, and more. Additionally, closures allow you to manipulate local variables outside of functions, providing greater flexibility and maintainability to your code.

Features of JavaScript Closures

  • Closures can access the variables of the outer function, even if the outer function has returned.
  • Closures hold references to variables outside the function, not actual values.
  • Closures are created whenever a function is created within another function.

Purpose of JS Closures

Closures are often used to:

  • Encapsulation  − Inner functions can access outer variables, but outer functions cannot access inner variables. This provides encapsulation and data privacy.
  • State Persistence  - Closures can persist state (such as a counter) across function calls. A function's variables persist between calls.
  • Partial Function Application  - Closures can be used for partial function application and curried functions. This involves creating a function that captures some parameters but leaves others unset.

Types of JS closures

1.  Ordinary closure

Ordinary closure means that a function defines another function inside, and the inner function refers to the variables of the outer function. In this case, the inner function captures the variables of the outer function and can continue to use them after the outer function finishes executing.

var outerVar = 'I am from outer'; function inner() { console.log(outerVar); } return inner; } var closureFunction = outer(); closureFunction(); // 输出:I am from outer

2.  Immediately Invoked Function Expression (IIFE) Closures

IIFE is a common pattern for creating closures. By wrapping the function definition in parentheses and calling it immediately, you can create a function that still has access to the outer scope after execution.

var privateVar = 'I am private'; return function() { console.log(privateVar); }; })(); closureFunction(); // 输出:I am private

Practice Case: Counter Closure

Let us further understand the application of closures through a practical example. Consider a simple counter, implemented with a closure:

var count = 0; return function() { return ++count; }; } var counter = createCounter(); console.log(counter()); // 输出:1 console.log(counter()); // 输出:2 console.log(counter()); // 输出:3

interactive exercise

1. Create a closure function to calculate the cumulative sum. The initial value of the function is 0, and each call will accumulate the parameter value into the internal variable. Reference answer:

var sum = 0; return function(value) { sum += value; return sum; }; } var sumCalculator = createSumCalculator(); console.log(sumCalculator(5)); // 输出:5 console.log(sumCalculator(10)); // 输出:15 console.log(sumCalculator(2)); // 输出:17 

2. Create an IIFE closure for generating the next value of the Fibonacci sequence. The Fibonacci sequence starts with 0 and 1, and each subsequent number is the sum of the previous two numbers. Reference answer:

var a = 0; var b = 1; return function() { var next = a + b; a = b; b = next; return next; }; })(); console.log(fibonacciGenerator()); // 输出:1 console.log(fibonacciGenerator()); // 输出:2 console.log(fibonacciGenerator()); // 输出:3

Precautions

  • Closures can cause memory leaks because closures retain references to outer scopes, and variables in outer scopes cannot be released by garbage collection.
  • Pay attention to the scope chain when using closures to avoid accidentally referencing variables you don't need.
  • Closures are not only useful in the browser, but are also used frequently in Node.js server-side programming.

Debug the backend interface through the API tool

Apifox is a   more powerful interface testing tool than Postman. Apifox = Postman + Swagger + Mock + JMeter. Apifox supports debugging interfaces of http(s), WebSocket, Socket, gRPC, Dubbo and other protocols, and integrates IDEA plug  - ins . When the back-end personnel finish writing the service interface, Apifox can be used to verify the correctness of the interface during the testing phase. The graphical interface greatly facilitates the online efficiency of the project.

Summarize

Closures are a powerful and interesting concept in JavaScript that allow inner functions to access variables and data in outer scopes. By creating closures, you can achieve privacy, encapsulation, and more advanced programming techniques. Understanding how closures work and applying them in real projects will make your JavaScript code more elegant and powerful.

Knowledge expansion:

Reference link:

Guess you like

Origin blog.csdn.net/m0_71808387/article/details/132447030