Scope and let, const

Scope and let, const

let command

1. The let command is only valid in the code block where it is located
. 2. There is a temporary dead zone
. 3. The let command does not allow repeated declarations
. 4. Let adds a new block-level scope to JavaScript.

var command

Variable hoisting: Variables declared with var will be declared at the top of the function (or globally) regardless of where they are actually declared.

Scope

The area where a variable or function works.

Global scope:
  	1、 在所有函数之外定义的变量拥有全局作用域,该变量为全局					      变量。
	2、全局变量可以在当前页面中任何JavaScript代码中访问。
Function scope:
	1、在函数中声明的变量(包括函数参数)指定在其所声明的函数内被访问。
Block scope:
	1、由{ }界定的代码区域,let声明的变量具备可访问块作用域。
	2、ES6允许块级作用域任意嵌套,一对{}即为一个块级作用域。
    3、内层作用域可以定义与外层作用域同名变量。
    4、块级作用域的出现使得ES5中惯用的IIFE(立即执行匿名函数)不再必要了。

const command

Basic usage

Declare a read-only constant. Once declared, its value cannot be changed and must be initialized immediately.
Otherwise, the usage is consistent with let.

substance
const foo={
    
    y:10};
foo.x=100;
console.log(foo.x);
foo={
    
    n:1000};

When a constant saves not a value but an address, the object referenced by the constant can change its members, but the address saved by the constant cannot be changed.

top-level object

1. The top-level object of the browser is window, and the top-level object of Node is global.
2. Variables defined by var will be associated with the top-level object, but let and const will not.

var a=100;//undedined
console.log(window.a);//100
let b=100;//undedined
console.log(window.b);//undefined

Summarize

The global variables declared by the let and const commands are not attributes of the top-level object. The
global variables declared by the var and function commands are attributes of the top-level object.

Guess you like

Origin blog.csdn.net/outaidered/article/details/115533896