


Detailed explanation of the use of javascript scope and closure_Basic knowledge
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:
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):
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.
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
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.
func.apply(target, arguments);
};
}
External functions cannot access embedded functions
External functions cannot access parameters and variables of embedded functionsBut 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:
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:
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:
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.

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

AI Hentai Generator
Generate AI Hentai for free.

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



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.

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.

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 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.

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.

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. 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.

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.
