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

Detailed explanation of js scope and closure

angryTom
Release: 2019-11-29 14:03:17
forward
2793 people have browsed it

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!

Related labels:
source:cnblogs.com
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template