ES6 block-level scope in detail

ES6 block-level scope in detail

  1. In ES5, there are only global scope and function scope, no block-level scope, and let actually adds block-level scope to JavaScript
        function f1() {
            let n = 5;
            if (true) {
                let n = 10;
            }
            console.log(n);
        }
        f1(); //5

The above code has two code blocks, both of which declare the variable n, but the output result is 5, indicating that the outer code block is not affected by the inner code block, but if var is used, the output result is 10.

        function f2() {
            var n = 5;
            if (true) {
                var n = 10;
            }
            console.log(n);
        }
        f2(); //10
  1. ES6 allows arbitrary nesting of block-level scopes. The outer scope cannot access the variables of the inner scope, but the inner scope can define variables with the same name in the outer scope.
        {
            {
                let n = 10;
            }
            console.log(n);//Error,不能在变量所在的块级作用域之外访问此变量
        }
  1. The emergence of block-level scope makes immediate execution of anonymous functions (IIFE) no longer necessary
        (function() {
            var temp;
        }());
        {
            let temp;
        }
        //上述立即执行匿名函数与let所在代码块的作用都是一样的,都是在块级作用域中声明变量temp

ES6 introduces the block-level scope, which explicitly allows functions to be declared in the block-level scope, and the function declaration statement behaves like let. It cannot be referenced outside the block-level scope and should be avoided in the block-level scope. Function, if it does not work, use the form of function expression instead of function declaration statement, and the declared function can only be placed in braces in the block-level scope

Guess you like

Origin blog.csdn.net/Angela_Connie/article/details/110761878