ES6 const command

const command similar to the let command, just let declare variables , declared const constants .

We const declare a read-only constants. Once declared, the value of the constant can not be changed;

Conventional writing:

const PI=3.333;
console.log(PI);

const instructions given situation:

       The first @: const End statement constant, unchangeable, being given once to change the constant value 
        const the PI = 3.333; 
        the PI =. 3; 
        the console.log (the PI); // error; Uncaught TypeError: Assignment to constant variable .
        
     

          const fun={};
      fun={};
      console.log(fun);//报错;Assignment to constant variable

      const a = [];
      a = [];
      console.log(a);

        // The second: const once declared, it must be initialized immediately, not later left to the assignment.
       
     A const; the console.log (A); // error; Missing initializer of Declaration in const // Third: const where the code block as a block-level scope, so that only the variables within the block-level action or closing wherein packages.      IF (to true) { const = M. 4; } the console.log (M); // error; M IS Not defined // Fourth: variable declared const variable does not exist lifting    IF (to true) {   the console.log (A ); // error; Can not Access 'A' before Initialization    const A = 10;      }    // fifth: not redeclaration variable    var Message = "the Hello!";    the let Age = 25; const Message = "Goodbye!"; const age = 30;

console.log (message); // error; Identifier 'message' has already been declared console.log(age);//报错;Identifier 'age' has already been declared

Nature:

By Ruan Yifeng teacher has said, constin fact, guaranteed, not the value of the variable may not change, but the memory address of the variable points of the stored data shall not be altered. For simple data type (numeric, string, Boolean), that value is stored in the memory address pointed to by the variable, and therefore equal to the constant. However, the composite type data (mainly objects and arrays), a variable memory address pointed to save only a pointer to the actual data, constonly the pointers are guaranteed (i.e., points to another fixed address always) fixed, As it points to the data structure is not a variable, it can not completely control. Therefore, an object declared as constants must be very careful.

const no error in the following situations

Person = const {}; // declare an object 
PERSON.NAME = 'WZX' ; // add object property 
person.age = 24 ; 
the console.log (PERSON.NAME); // 

const Number = []; // declare an array 
number.push ( 4,5 ); // add array 
console.log (number);

Output:

 

If you want to freeze the object itself, you can use Object.freeze () method.

 

const person=Object.freeze({});
    person.name="wzx";
    console.log(person.name); //undefined

 

Guess you like

Origin www.cnblogs.com/smile-xin/p/11401807.html