Home Web Front-end JS Tutorial Detailed explanation of js scope and closure

Detailed explanation of js scope and closure

Nov 29, 2019 pm 02:02 PM
Scope Closure

Detailed explanation of js scope and closure

Scope

There are two types of scope in JS: global scope|local scope

Lizi 1

console.log(name);      //undefined
var name = '波妞';
var like = '宗介'
console.log(name);      //波妞
function fun(){
    console.log(name);  //波妞
    console.log(eat)    //ReferenceError: eat is not defined
    (function(){
        console.log(like)   //宗介
        var eat = '肉'
    })()
}
fun();
Copy after login

[Related course recommendations: JavaScript Video Tutorial]

1. The name is defined globally and can be accessed globally, so (2) Printing can be printed correctly;

2. In function fun, if the name attribute is not defined, it will be found in its parent scope, so (3) can also be printed correctly.

3. The internal environment can access all external environments through the scope chain, but the external environment cannot access any variables and functions of the internal environment. Similar to One-way transparency, this is a scope chain, so (4) is not possible but (5) is.

Then the question arises, why the first print is "undefined" instead of "ReferenceError: name is not defined". The principle is simply the variable promotion of JS

Variable promotion: When JS parses the code, it will advance all declarations to the front of the scope


Chestnut 2

console.log(name);      //undefined
var name = '波妞';
console.log(name);      //波妞
function fun(){
    console.log(name)   //undefined
    console.log(like)   //undefined
    var name = '大西瓜';
    var like = '宗介'
}
fun();
Copy after login

is equivalent to

var name;
console.log(name);      //undefined
name = '波妞';
console.log(name);      //波妞
function fun(){
    var name;
    var like;
    console.log(name)   //undefined
    console.log(like)   //undefined
    name = '大西瓜';
    like = '宗介'
    console.log(name)   //大西瓜
    console.log(like)   //宗介
}
fun();
Copy after login

Note: is advanced to the current scope The front


Chestnut 3

printName();     //printName is not a function
var printName = function(){
    console.log('波妞')
}
printName();       //波妞
Copy after login

is equivalent to

var printName;
printName();     //printName is not a function
printName = function(){
    console.log('波妞')
}
printName();       //波妞
Copy after login

This way it is easy to understand, the function expression is in When declared, it is just a variable


Chestnut 4

{
    var name = '波妞';
}
console.log(name)   //波妞

(function(){
    var name = '波妞';
})()
console.log(name)   //ReferenceError: name is not defined

{
    let name = '波妞';
}
console.log(name)   //ReferenceError: name is not defined
Copy after login

As can be seen from the above chestnut, variables declared by var in JS cannot be hastily considered The scope of is the starting and ending scope of the curly braces. ES5 does not have a block-level scope, but is essentially a function scope. Only after the let and const definitions were introduced in ES6, there was a block-level scope.


Chestnut 5

function p1() { 
    console.log(1);
}
function p2() { 
    console.log(2);
}
(function () { 
    if (false) {
        function p1() {
            console.log(3);
        }
    }else{
        function p2(){
            console.log(4)
        }
    }
    p2();
    p1()
})();       
//4
//TypeError: print is not a function
Copy after login

This is a very classic chestnut. The declaration is made in advance, but because the judgment condition is no, the function body is not executed. So "TypeError: print is not a function" will appear. The same applies to while, switch, and for

closure

The function and the reference to its state, that is, the lexical environment (lexical environment) together form a closure. ). That is, closures allow you to access the outer function scope from the inner function. In JavaScript, functions generate closures every time they are created.

The above definition comes from MDN. Simply put, a closure refers to a function that has the right to access variables in the scope of another function.


● The key to closure is that its variable object should have been destroyed after the external function is called, but the existence of the closure allows us to still access the variable object of the external function. ,

//举个例子
function makeFunc() {
    var name = "波妞";
    function displayName() {
        console.log(name);
    }
    return displayName;
}

var myFunc = makeFunc();
myFunc();
Copy after login

Functions in JavaScript form closures. A closure is composed of a function and the lexical environment that creates the function. This environment contains all local variables that can be accessed when this closure is created

In the example, myFunc is a reference to the displayName function instance created when makeFunc is executed, and the displayName instance can still access its lexical Variables in the scope can access name. Thus, when myFunc is called, name can still be accessed, and its value 'Ponyo' is passed to console.log. The most common way to create a closure is to create another function inside a function


● Usually, the scope of a function and all its variables will end at the end of function execution was later destroyed. However, after creating a closure, the scope of the function will be saved until the closure no longer exists

//例二
function makeAdder(x) {
  return function(y) {
    return x + y;
  };
}

var add5 = makeAdder(5);
var add10 = makeAdder(10);

console.log(add5(2));  // 7
console.log(add10(2)); // 12

//释放对闭包的引用
add5 = null;
add10 = null;
Copy after login

Essentially, makeAdder is a function factory - he creates the A function that adds the sum of a specified value and its arguments. In the example above, we used the function factory to create two new functions—one that sums its arguments plus 5 and another that sums 10 .

add5 and add10 are both closures. They share the same function definition, but store different lexical environments. In the context of add5, x is 5. And in add10, x is 10.

The scope chain of a closure includes its own scope, as well as the scope of the containing function and the global scope.


● Closure can only obtain the last value of any variable in the containing function

//栗子1
function arrFun1(){
    var arr = [];
    for(var i = 0 ; i < 10 ; i++){
        arr[i] = function(){
            return i
        }
    }
    return arr
}
console.log(arrFun1()[9]());     //10
console.log(arrFun1()[1]());     //10

//栗子2
function arrFun2(){
    var arr = [];
    for(var i = 0 ; i < 10 ; i++){
        arr[i] = function(num){
            return function(){
                return num
            };
        }(i)
    }
    return arr
}
console.log(arrFun2()[9]());     //9
console.log(arrFun2()[1]());     //1
Copy after login

In example 1, the arr array contains 10 Each anonymous function can access the external variable i. After arrFun1 is executed, its scope is destroyed, but its variables still exist in memory and can be accessed by anonymous functions in the loop. In this case, i is 10;

In Chestnut 2, there is an anonymous function in the arr array, and there are anonymous functions within the anonymous function. The num accessed by the innermost anonymous function is saved in the memory by the upper-level anonymous function, so it can be accessed. to the value of i each time.

This article comes from the js tutorial column, welcome to learn!

The above is the detailed content of Detailed explanation of js scope and closure. For more information, please follow other related articles on the PHP Chinese website!

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

Video Face Swap

Video Face Swap

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

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.

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.

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.

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.

The difference between let and var in vue The difference between let and var in vue May 08, 2024 pm 04:21 PM

In Vue, there is a difference in scope when declaring variables between let and var: Scope: var has global scope and let has block-level scope. Block-level scope: var does not create a block-level scope, let creates a block-level scope. Redeclaration: var allows redeclaration of variables in the same scope, let does not.

See all articles