Home > Article > Web Front-end > What scopes were introduced in es6
The "block-level scope" was introduced in es6; in es5, there are only global scope and function scope. In es6, the scope formed by a pair of curly brackets is the block-level scope, and it is explicitly allowed to When a function is declared in a block-level scope, the function declaration statement behaves like let and cannot be referenced outside the block-level scope.
The operating environment of this tutorial: Windows 10 system, ECMAScript version 6.0, Dell G3 computer.
ES6 introduced block-level scope, explicitly allowing functions to be declared in block-level scope. ES6 stipulates that in block-level scope, function declaration statements behave like let and cannot be referenced outside block-level scope.
In the ES6 standard, the scope formed by a pair of braces is the block-level scope.
ES5 stipulates that functions can only be declared in the top-level scope and function scope, and cannot be declared in the block-level scope.
ES5 only has global scope and function scope, but no block-level scope, which brings many unreasonable scenarios.
(1) Inner variables may overwrite outer variables.
var tmp = new Date(); function f() { console.log(tmp); if (false) { var tmp = 'hello world'; } } f();//undefined
(2) The loop variable used for counting is leaked into a global variable
var s = 'hello'; for (var i = 0; i < s.length; i++) { console.log(s[i]);//h e l l o } console.log(i);//5
The variable i is only used to control the loop, but after the loop ends, it does not disappear and is leaked into a global variable .
An example is as follows:
// 浏览器的 ES6 环境 function f() { console.log('I am outside!'); } (function () { if (false) { // 重复声明一次函数f function f() { console.log('I am inside!'); } } f(); }()); // Uncaught TypeError: f is not a function
In the ES6 standard, when a function is declared in a block-level scope, the function declaration will be regarded as a variable declared by var and will be promoted to the top of the block-level scope. When the function is used as a variable and the variable name is declared, the function body will not be declared. The above code is equivalent to:
// 浏览器的 ES6 环境 function f() { console.log('I am outside!'); } (function () { var f = undefined; if (false) { function f() { console.log('I am inside!'); } } f(); }()); // Uncaught TypeError: f is not a function
[Related recommendations: javascript video tutorial, web front-end 】
The above is the detailed content of What scopes were introduced in es6. For more information, please follow other related articles on the PHP Chinese website!