Home Web Front-end JS Tutorial JavaScript closures - the scope of closures

JavaScript closures - the scope of closures

Jan 20, 2017 pm 02:17 PM

Closure is a very important concept in JavaScript. Closure means that a copy of the variables (key-value pairs) obtained from the upper-level function or scope is saved in another scope, and these key-value pairs will not be closed as the execution of the upper-level function is completed. Destroyed. Closure essentially discusses when the member properties of an object are processed by GC (garbage collection mechanism).

We have actually come into contact with closures in the value transfer of the previous function. When explaining function value transfer, we listed a function sortByProperty that compares object properties. In this function, its return value is an anonymous function, which is actually a closure. We still use this example to explain the scope of closures. The code of this function is slightly modified as follows:

// 比较对象属性大小的通用函数
function compareObjectFunction(prop){
  //匿名函数
  return function(obj1,obj2){
    if(obj1[prop] > obj2[prop]) return 1;
    else if(obj1[prop] < obj2[prop]) return -1;
    else return 0;
  }
}
// 创建2个对象
var o1 = {name:"Leon",age:22}
var o2 = {name:"Ada",age:25}
// 比较对象的name属性
var compare = compareObjectFunction("name");
// 返回值
var returnValue = compare(o1,o2);
console.info(rel);  //比较name属性会返回1,比较age属性会返回-1
Copy after login

In the above example, the biggest benefit of using closures is that the scope of compareObjectFunction has become larger. After the compareObjectFunction function is executed, the prop variable still exists. .

In static object-oriented programming languages ​​such as java and C++, after executing the sentence var compare = compareObjectFunction("name"), the memory will be released and the prop attribute will be garbage collected. But in JavaScript, when the code is executed to var rel = compare(o1,o2);, you can still access the prop attribute. This method of expanding the scope of a function by returning a function is a closure.

One thing to note is: closure is not equal to anonymous function. The way we create closures is usually by creating a function inside another function. So, how does a closure enlarge the scope of a function? We still use the scope memory model when the function is executed to explain this problem.

First we created the compareObjectFunction function, and then created 2 objects o1 and o2. After completing these codes, the scope chain model in memory is as shown below:

JavaScript closures - the scope of closures

The high bit of the scope chain of compareObjectFunction points to the global scope, and the low bit points to its own scope. There are 3 variables in the global scope at this time.

Next, start comparing the name attribute of the object and execute the following code:

var compare = compareObjectFunction("name");
var returnValue = compare(o1,o2);
Copy after login

Compare the name sizes of the two objects by passing name as a parameter into the compareObjectFunction function. After executing the above two lines of code, the memory model of the scope chain is as shown below:

JavaScript closures - the scope of closures

When the compareObjectFunction function is executed, it returns an anonymous function, anonymous A function also has its scope chain. Its high bit points to the global scope, the middle bit points to the scope containing its compareObjectFunction, and the low bit points to its own scope.

After the program executes the compareObjectFunction("name") code, the compareObjectFunction function is executed and the GC begins to recycle it. But then the GC will find that there is another anonymous function pointing to the scope of compareObjectFunction. At this time, the GC will not reclaim this scope memory. The scope chain of compareObjectFunction and the memory of the function itself will be garbage collected by GC.

When the program executes compare(o1,o2), it first changes the values ​​​​of obj1 and obj2 to o1 and o2 respectively in its own scope, and then it needs to call the prop attribute, because in its own scope If this attribute is not found in the scope space, it will search in the scope compareObjectFunction pointed to by the upper level of the linked list. At this time, it finds that the prop attribute is name, so it uses the name attribute to compare and get the return value.

It can be seen that it is precisely because an anonymous function points to the scope of compareObjectFunction that after the compareObjectFunction function is executed, its scope space will not be garbage collected by GC, thereby reducing the role of the prop attribute. The domain is enlarged.

Although JavaScript's closure can enlarge the scope of the function, the price is that it will occupy more memory space when the program is executed, so we cannot abuse closures and only use them when needed. it.

The above is the content of JavaScript closure-closure scope. For more related content, please pay attention to the PHP Chinese website (www.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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Usage of typedef struct in c language Usage of typedef struct in c language May 09, 2024 am 10:15 AM

typedef struct is used in C language to create structure type aliases to simplify the use of structures. It aliases a new data type to an existing structure by specifying the structure alias. Benefits include enhanced readability, code reuse, and type checking. Note: The structure must be defined before using an alias. The alias must be unique in the program and only valid within the scope in which it is declared.

How to solve variable expected in java How to solve variable expected in java May 07, 2024 am 02:48 AM

Variable expected value exceptions in Java can be solved by: initializing variables; using default values; using null values; using checks and assignments; and knowing the scope of local variables.

What does include mean in c++ What does include mean in c++ May 09, 2024 am 01:45 AM

The #include preprocessor directive in C++ inserts the contents of an external source file into the current source file, copying its contents to the corresponding location in the current source file. Mainly used to include header files that contain declarations needed in the code, such as #include <iostream> to include standard input/output functions.

Advantages and disadvantages of closures in js Advantages and disadvantages of closures in js May 10, 2024 am 04:39 AM

Advantages of JavaScript closures include maintaining variable scope, enabling modular code, deferred execution, and event handling; disadvantages include memory leaks, increased complexity, performance overhead, and scope chain effects.

How to implement closure in C++ Lambda expression? How to implement closure in C++ Lambda expression? Jun 01, 2024 pm 05:50 PM

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.

C++ smart pointers: a comprehensive analysis of their life cycle C++ smart pointers: a comprehensive analysis of their life cycle May 09, 2024 am 11:06 AM

Life cycle of C++ smart pointers: Creation: Smart pointers are created when memory is allocated. Ownership transfer: Transfer ownership through a move operation. Release: Memory is released when a smart pointer goes out of scope or is explicitly released. Object destruction: When the pointed object is destroyed, the smart pointer becomes an invalid pointer.

Can the definition and call of functions in C++ be nested? Can the definition and call of functions in C++ be nested? May 06, 2024 pm 06:36 PM

Can. C++ allows nested function definitions and calls. External functions can define built-in functions, and internal functions can be called directly within the scope. Nested functions enhance encapsulation, reusability, and scope control. However, internal functions cannot directly access local variables of external functions, and the return value type must be consistent with the external function declaration. Internal functions cannot be self-recursive.

There are several situations where this in js points to There are several situations where this in js points to May 06, 2024 pm 02:03 PM

In JavaScript, the pointing types of this include: 1. Global object; 2. Function call; 3. Constructor call; 4. Event handler; 5. Arrow function (inheriting outer this). Additionally, you can explicitly set what this points to using the bind(), call(), and apply() methods.

See all articles