Home Web Front-end JS Tutorial Detailed explanation of the use of javascript scope and closure_Basic knowledge

Detailed explanation of the use of javascript scope and closure_Basic knowledge

May 16, 2016 pm 04:51 PM
Scope Closure

The nesting of scopes will form a scope chain, and the nesting of functions will form a closure. Closures and scope chains are one of the important features that distinguish JavaScript from other languages.

Scope
There are two types of scope in JavaScript: function scope and global scope.

Variables declared in a function and the parameters of the function share the same scope, that is, the function scope. A simple example of function scope:

Copy code The code is as follows:

function foo() {
var bar = 1 ;
{
var bar = 2;
}
return bar; // 2
}

Unlike other block-scoped languages ​​such as C, this will always return 2 .

Global scope, for browsers, can be understood as the window object (Node.js is global):

Copy code The code is as follows:

var bar = 1;
function foo() {}
alert(window.bar); // 1
alert(window.foo) ; // "function foo() {}"

Both the variable bar and the function foo belong to the global scope and are both attributes of window.

Scope chain
When accessing a variable in JavaScript, it will start from local variables and parameters and traverse the scope step by step until it reaches the global scope.

Copy code The code is as follows:

var scope = 0, zero = "global-scope" ;
(function(){
var scope = 1, one = "scope-1";
(function(){
var scope = 2, two = "scope-2";
(function(){
var scope = 3, three = "scope-3";
scope-1 global-scope
console.log([three, two, one, zero].join(" "));
              console.log(scope); // 3
           })(); 🎜> console.log(scope); // 2
})();
console.log(typeof two); // undefined
console.log(scope); // 1
})();
console.log(typeof one); // undefined
console.log(scope); // 0


In the innermost function, each variable can be traversed step by step and output. In the penultimate layer of functions, the variable three cannot be found by traversal, so undefined is output.

To give a simple example, when you are going to spend money to buy something, you will first touch your wallet. If you don’t have it, you can ask your dad for it. If your dad doesn’t have it, you can ask your grandpa... And when your dad doesn’t have money to buy something, he won’t come to you to ask for it.

Closure

In one function, defining another function is called function nesting. The nesting of functions will form a closure.


Closures and scope chains complement each other. The nesting of functions not only creates multiple scopes in a chain relationship, but also forms a closure.


function bind(func, target) {
return function() {
func.apply(target, arguments);
};
}


So how do you understand closure?

External functions cannot access embedded functions

External functions cannot access parameters and variables of embedded functions

But embedded functions can access parameters and variables of external functions
In other words: embedded functions Contains the scope of the external function
Let’s look at the scope chain example mentioned before, this time understanding it from the perspective of closure:

Copy code The code is as follows:

var scope = 0, zero = "global-scope";
(function(){
var scope = 1, one = "scope-1";
(function() {
var scope = 2, two = "scope-2";
(function(){
var scope = 3, three = "scope-3";
// scope-3 scope -2 scope-1 global-scope
console.log([three, two, one, zero].join(" "));
console.log(scope); // 3
}) ();
console.log(typeof three); // undefined
console.log(scope); // 2
})();
console.log(typeof two); / / undefined
console.log(scope); // 1
})();
console.log(typeof one); // undefined
console.log(scope); // 0

The innermost function can access all variables defined internally and externally. The penultimate layer function cannot access the innermost variable. At the same time, the assignment operation of scope = 3 in the innermost layer does not affect the external variable of the same name.

Let’s understand closure from another angle:

Each time an external function is called, the embedded function will be created once
When it is created, the scope of the external function (including any local variables, parameters, etc. context) will become each embedded function object part of the internal state, even after the external function completes execution and exits
See the following example:

Copy code The code is as follows:

var i, list = [];
for (i = 0; i < 2; i = 1) {
list.push(function(){
console.log(i);
});
}
list .forEach(function(func){
func();
});

We will get "2" twice instead of the expected "1" and "2". This is because the variable i accessed by the two functions in the list is the same variable in the upper scope. .

Let’s change the code to use closures to solve this problem:

Copy code The code is as follows:

var i, list = [];
for (i = 0; i < 2; i = 1) {
list.push((function(j){
) return function(){
console.log(j);
} ;
})(i));
}
list.forEach(function(func){
func();
});

The outer "immediate execution function" receives a parameter variable i, which exists in the form of parameter j within its function. It points to the same reference as the name j in the returned inner function. After the outer function executes and exits, parameter j (its value is the current value of i at this time) becomes part of the state of its inner function and is saved.

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