let const var summary

written in front

The text in this format is for personal understanding, pure vernacular

Adding * before the title of the article means that the knowledge point is difficult to understand or easy to miss

1. var keyword

1.1 There is no concept of block-level scope, but the concept of global scope and function scope

Example 1:

//Global Scope
{
    
    
  var a = 10;
}
console.log(a);  //10

Declare a inside the curly braces, and it can still be accessed outside the curly braces. It can be seen that the variable declared by var does not have the concept of block scope (Block Scope)

Example 2:

//Global Scope
var a = 10;
function checkscope(){
    
    
    //Local Scope
    var b = 20;
    console.log(a);  //10
    console.log(b);  //20
}
checkscope();
console.log(b);  //ReferenceError: b is not defined

In the above code, a is declared with var in the Global Scope , and 10 is printed in the Local Scope (local scope, function scope) in the checkscope function , but the variable b printed in the Global Scope reports an error.

A is declared globally, exists in the global scope, and can also be accessed inside the function (checkscope). Variables declared inside the function (checkscope) only exist in the scope of the function and cannot be accessed outside the function

1.2 There is variable promotion

Example 3:

//Global Scope
console.log(a);  //undefined
var a = 10;

checkscope();
function checkscope(){
    
    
    //Local Scope
    console.log(a);  //undefined
    var a;
}

First print a, and then use var to declare variable a, and the print result is undefined.
Variable hoisting is because js needs to manage compile and execute phases. When js is in the compilation phase, it will collect all variable declarations and declare variables in advance

1.3 Variables declared with var in the global scope will be mounted on the window object

//Global Scope
var a = 10;
console.log(a);  //10
console.log(window.a);  //10
console.log(this.a);  //10

In the above code, three 10s are printed , and accessing a is equivalent to window.a or this.a.
For example: For example, if I want to access the location object, I can access it by using location , and I can also access it by using window.location , but the window object can be omitted, just like new Array( ) and new window.Array( ) are equivalent .

1.4 Duplicate declarations are allowed in the same scope

//Global Scope
var a = 10;
var a = 20;
console.log(a);  //20

checkscope();
function checkscope(){
    
    
    //Local Scope
    var b = 10;
    var b = 20;
    console.log(b);  //20
}

In the above code, a is declared twice in the Global Scope , and the last declaration is effective, and it is printed as 20 . In the same way, it is the same in Local Scope .

1.5 The uninitialized value defaults to undefined

//Global Scope
var a;
console.log(a);  //undefined

A is declared with var in Global Scope , but there is no initialized value, and its value is undefined by default. Here, undefined is an undefined type, not a string.

2.let keyword

2.1 There is a concept of block-level scope

{
    
    
   //Block Scope
   let a = 10;
}
console.log(a);  //ReferenceError: a is not defined

Variables declared inside curly braces cannot be accessed outside the braces

2.2 There is no variable promotion

 console.log(a);  // Uncaught ReferenceError: a is not defined
  let a = 10;

In the above code, printing a reports an error: cannot be accessed before initialization. Indicates that there is no variable hoisting.

2.3 Duplicate declarations are not allowed in the same scope

{
    
    
  //Block Scope
  let A;
  var A;  //SyntaxError: Identifier 'A' has already been declared
}
{
    
    
  //Block Scope
  var A;
  let A;  //SyntaxError: Identifier 'A' has already been declared
}
{
    
    
  //Block Scope
  let A;
  let A;  //SyntaxError: Identifier 'A' has already been declared
}

*2.4 Temporary dead zone (dead zone)

There is a temporary dead zone between the first line in the scope and the statement using let and const, and an error will be reported when accessing the variable.

Explanation in the ECMAScript2015 document: When the control flow of the program is instantiated
in a new scope ( module, function or block scope), variables declared with let/const in this scope will be created in the scope first Come out, but because the lexical binding has not been performed at this time, it cannot be accessed, and an error will be thrown if accessed. Therefore, the period between when the running process enters the scope to create variables and when the variables can be accessed is called a temporary dead zone.

Personal understanding: The let/const command will make the block form a closed scope. In this scope , the variable declared by let/const* will be created in the scope first. Until the variable is declared, the variable is If it is not available, the access will report an error. Syntactically called "temporal dead zone" ( temporal dead zone , TDZ for short )

if (true) {
    
    
  //暂时性死区(TDZ)开始
  console.log(a);  //ReferenceError: Cannot access 'a' before initialization

  let a; //暂时性死区(TDZ)结束
  console.log(a);  //undefined

  a = 123;
  console.log(a);  //123
}

Example 4:

{
    
    
  //Block Scope
  console.log(a);  //ReferenceError: Cannot access 'a' before initialization
  let a = 20;
}

Exclusive error: cannot access the difference before initialization
insert image description here
:

The temporary dead zone here exists in the block-level scope. If it is in the global scope, an error 'is not defined' will be reported

insert image description here

3. const keyword

In addition to the four characteristics of let above ( there is block-level scope, no variable promotion, repeated declarations are not allowed in the same scope, and there is a temporary dead zone ), const also has the following characteristics:

3.1 It must be initialized immediately after creation, and cannot be left for later assignment

insert image description here
The variable a declared with const is not initialized, so an error is reported.

*3.2 Create constants

The characteristics of const to create constants:

What const actually guarantees is not that the value of the variable cannot be changed, but that the memory address pointed to by the variable cannot be changed.
For simple types of data (numbers, strings, booleans), the value is stored at the memory address pointed to by the variable, so it is equivalent to a constant. But for composite types of data (mainly objects and arrays), the memory address pointed to by the variable stores only a pointer, and const can only guarantee that the pointer is fixed. As for whether the data structure it points to is variable or not, this Totally out of control.

Example 5:
insert image description here

The memory address of the variable created by const cannot be changed, and for simple data types, the value exists in the memory address pointed to by the variable, and the value of all a cannot be changed. Example 6: For complex data types, the memory address is
stored
insert image description here
in A pointer, const can only guarantee that the pointer is fixed, and the data structure pointed to by the pointer can be changed

3.2.1 es5 implements creating constants

Object.defineProperty
has three parameters:

  1. The object where the attribute resides
  2. attribute name
  3. A descriptor object:
    • Configurable: Indicates whether the attribute can be deleted through delete to redefine the attribute, whether the attribute can be modified, or whether the attribute can be modified as an accessor attribute. The default value is false.
    • enumerable: Indicates whether the attribute can be accessed through for in loop, the default value is false
    • writable: Indicates whether the value of the attribute can be modified. The default value is false.
    • value: Contains the data value of this attribute. The default value is undefined.

accomplish:

Object.defineProperty(window,"args",{
    
    
value: ' this is es5',
writable: false
})

Error: constant variable assignment
insert image description here

3.2.1 Implement the reference type created by const as a constant
const obj={
    
    
 id:1,
 age:18,
 name:'aaa'
}

obj.age=19       // cosnt 创建一个对象,对象中的属性可以被改变

Question 1: How to make the properties in the object immutable
Solution: Use Object.freeze() to freeze the object, a frozen object can no longer be modified

const obj2={
    
    
 id:2,
 name:'bbb',
 age:20,
 food:['banana','apple']
}
Object.freeze(obj2)

obj2.age=21                 //被Object.freeze()冻结后,不可以改变    
obj2.foods[1]='pear'        //可以改变  freeze只能冻结根层 嵌套引用类型需要嵌套递归

Solution: Realize the creation of reference types
Idea: Use recursion to freeze the reference types of each layer and realize the creation of constants of reference types.

   function deepFreeze(obj) {
    
    
            Object.freeze(obj);
            (Object.keys(obj) || []).forEach((key) => {
    
    
                let innerObj = obj[key]
                if (typeof innerObj === 'object') {
    
    
                    deepFreeze(innerObj);
                }
            }
            )
        }


        const tempObj = {
    
    
            id: 23,
            name: '1',
            food: ['banana', 'apple']
        }
        deepFreeze(tempObj)

Guess you like

Origin blog.csdn.net/weixin_44247866/article/details/128061972