Sample code sharing for JS closure usage
This article mainly introduces the usage of JS closures, and analyzes the principles, execution steps and related operation techniques of javascript closures in combination with specific examples. Friends in need can refer to it. The following
examples in this article describe the usage of JS closures. Share it with everyone for your reference, the details are as follows:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> </head> <body> <script type="text/javascript"> // 第一,函数作为返回值 function fn(){ var max = 10; return function bar(x){ if(x > max) { console.log(x); } }; } var f1 = fn(); f1(15); </script> <script type="text/javascript"> // 第二,函数作为参数被传递 var max = 10; fn = function(x){ if(x > max){ console.log(x);//15 } }; (function(f){ var max = 100; f(15); })(fn); </script> <script> function fn(){ var max = 10; return function bar(x){ if(if > max){ console.log(x); } }; } var f1 = fn(); max = 100; f1(15); </script> </body> </html>
The first step is to generate the global context environment before the code is executed, and to perform operations on the variables during execution. Assignment. The global context is active at this time.
Global context environment: max is undefined
The second step, when executing the var f1 = fn(); code, call fn(), resulting in fn() execution The context is pushed onto the stack and set to the active state.
fn() context: max is 10
The third step, after executing var f1 = fn();, the fn() call is completed. It stands to reason that the execution context of fn() should be destroyed, but this cannot be done here.
Note, here comes the important point: because when fn() is executed, a function is returned. The special thing about functions is that they can create an independent scope.
Coincidentally, in the returned function body, there is also a free variable max that refers to max in the context of fn() in the fn scope.
Therefore, this max cannot be destroyed. After it is destroyed, the max in the bar function cannot find the value. Therefore, the fn() context here cannot be destroyed and still exists in the execution context stack.
When execution reaches max = 100;, the global context will become active, but the fn() context will still be in the execution context stack.
In addition, after max = 100; is executed, max in the global context is assigned a value of 100.
Global context: max is 100 fn() context: max is 10
The fourth step, execute to f1(15);, execute f1(15 ), that is, execute bar(15), create the bar(15) context, and set it to the active state.
When executing bar(15), max is a free variable. You need to search in the scope where the bar function was created, and the value of max is found to be 10.
The key point here is that the bar function is created when fn() is executed. The execution of fn() has ended long ago, but the execution context of fn() still exists on the stack, so when bar(15), max can be found. If the fn() context is destroyed, then max cannot be found.
Using closures will increase content overhead, it’s obvious now!
The fifth step, after executing f1(15); is the destruction process of the context environment, which will not be described here.
Closures are inseparable from scope and context. It’s really “it’s not easy to love you”!
In addition, closures have many applications in jQuery, whether you want to learn about a classic framework/class library, or If you want to develop a plug-in or class library yourself, you must know basic theories such as closures and prototypes. Otherwise, when bugs appear, you won’t know why, because these bugs may be completely outside the scope of your knowledge.
The above is the detailed content of Sample code sharing for JS closure usage. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Face detection and recognition technology is already a relatively mature and widely used technology. Currently, the most widely used Internet application language is JS. Implementing face detection and recognition on the Web front-end has advantages and disadvantages compared to back-end face recognition. Advantages include reducing network interaction and real-time recognition, which greatly shortens user waiting time and improves user experience; disadvantages include: being limited by model size, the accuracy is also limited. How to use js to implement face detection on the web? In order to implement face recognition on the Web, you need to be familiar with related programming languages and technologies, such as JavaScript, HTML, CSS, WebRTC, etc. At the same time, you also need to master relevant computer vision and artificial intelligence technologies. It is worth noting that due to the design of the Web side

In C++, a closure is a lambda expression that can access external variables. To create a closure, capture the outer variable in the lambda expression. Closures provide advantages such as reusability, information hiding, and delayed evaluation. They are useful in real-world situations such as event handlers, where the closure can still access the outer variables even if they are destroyed.

C++ Lambda expressions support closures, which save function scope variables and make them accessible to functions. The syntax is [capture-list](parameters)->return-type{function-body}. capture-list defines the variables to capture. You can use [=] to capture all local variables by value, [&] to capture all local variables by reference, or [variable1, variable2,...] to capture specific variables. Lambda expressions can only access captured variables but cannot modify the original value.

A closure is a nested function that can access variables in the scope of the outer function. Its advantages include data encapsulation, state retention, and flexibility. Disadvantages include memory consumption, performance impact, and debugging complexity. Additionally, closures can create anonymous functions and pass them to other functions as callbacks or arguments.

Title: Memory leaks caused by closures and solutions Introduction: Closures are a very common concept in JavaScript, which allow internal functions to access variables of external functions. However, closures can cause memory leaks if used incorrectly. This article will explore the memory leak problem caused by closures and provide solutions and specific code examples. 1. Memory leaks caused by closures The characteristic of closures is that internal functions can access variables of external functions, which means that variables referenced in closures will not be garbage collected. If used improperly,

The relationship between js and vue: 1. JS as the cornerstone of Web development; 2. The rise of Vue.js as a front-end framework; 3. The complementary relationship between JS and Vue; 4. The practical application of JS and Vue.

Yes, code simplicity and readability can be optimized through chained calls and closures: chained calls link function calls into a fluent interface. Closures create reusable blocks of code and access variables outside functions.

Go language function closures play a vital role in unit testing: Capturing values: Closures can access variables in the outer scope, allowing test parameters to be captured and reused in nested functions. Simplify test code: By capturing values, closures simplify test code by eliminating the need to repeatedly set parameters for each loop. Improve readability: Use closures to organize test logic, making test code clearer and easier to read.
