When we use the Const declaration constants, we always think that once the value declaration is immutable, there is actually a misunderstanding;
Just look at the ES6 standard document, carefully read the resolution of the const, the feeling of epiphany, share to everyone.
Essence
const
In fact, the value of the variable is not changed, but the memory address that the variable points to cannot be changed. For a simple type of data (numeric, String, Boolean), the value is stored in the memory address that the variable points to, so it is equivalent to a constant.
but for composite types of data (mostly objects and arrays), the memory address that the variable points to is just a pointer, which const
can only guarantee that the pointer is fixed, and that the data structure it points to is not variable, and it is completely out of control. Therefore, it must be very careful to declare an object as a constant.
const foo = {}; // Add a property to Foo to successfully 123 /// 123// to point Foo to another object, error // TypeError: "foo" is Read-only
In the above code, foo
a constant stores an address that points to an object. Immutable is just this address, that is, cannot foo
point to another address, but the object itself is mutable, so you can still add new properties for it.
Here is another example.
const A = [];a.push ('Hello'// executable 0; // executable a = ['Dave']; // Error
In the above code, the constant a
is an array, and the array itself is writable, but if you assign another array a
, you will get an error.
If you really want to freeze an object, you should use the Object.freeze
method.
const foo = object.freeze ({}); // Normal mode, the following line does not work; // Strict mode, the Guild error 123;
In the above code, the constant foo
points to a frozen object, so adding a new property does not work, and the strict mode will also cause an error.
In addition to freezing the object itself, the object's properties should also be frozen. The following is a function that completely freezes an object.
var constantize = (obj) + { object.freeze (obj); = = {iftypeof'object' ) { constantize ( Obj[key]); };
JS uses const to declare the nature of constants