Scope and function scope variables js

cited from

1. Scope of the variable (and let the difference var)

Variable outside the function declaration, called a global variable, because it can be accessed by any other code in the current document. In the variable declared inside a function, called a local variable, because it can only be accessed within the current function.

JavaScript statements before 6 ECMAScript not block scope; contrast, the variable declaration statement block will be the statement where the function block (or global scope) local variable. For example, the following code will be output in the console 5, because the  x scope is a statement  x that the function (or global scope), rather than  if block.

if (true) { var x = 5; } console.log(x); // 5

如果使用 ECMAScript 6 中的 let 声明,上述行为将发生变化。
if (true) { let y = 5; } console.log(y); // ReferenceError: y 没有被声明


2. 变量的提升
含义为: 先使用变量稍后再声明变量而不会引发异常, 但是提升后的变量将返回undefined值
变量提升即相当于:
var x;
console.log(x); // undefinded

示例:
/**
 * 例子1
 */
console.log(x === undefined); // true var x = 3; /** * 例子2 */ // will return a value of undefined var myvar = "my value"; (function() { console.log(myvar); // undefined var myvar = "local value"; })();

The above example can also be written (corresponding to the var x; console.log (x))
/**
 * 例子1
 */
var x;
console.log(x === undefined); // true x = 3; /** * 例子2 */ var myvar = "my value"; (function() { var myvar; console.log(myvar); // undefined myvar = "local value"; })();

Because of variable lift, a function of all the varstatements should be placed near the top of the function as much as possible. This habit will greatly enhance the clarity of your code.

 

However, let variable block-level scope, the variable lift will not exist

In ECMAScript 6, let (const) will not lift variable to the top of the code block. Therefore, the reference that variable before the variable declaration, will throw reference error (ReferenceError). This variable is a block from the start when he is in a "temporary dead zone" until the variable is declared so far.

console.log(x); // ReferenceError let x = 3;
 

Guess you like

Origin www.cnblogs.com/yanjijiang/p/11294692.html