JS defines const constant object

The new const keyword in ES6 is used to declare to create a read-only reference.

But it only stipulates that the identifier of the variable cannot be reassigned. For example, when the variable is declared as a reference type, the immutable is only the pointer bound to the variable (the concept does not exist in JS, which means that the value of the variable is the memory address stored in the stack. It will automatically address the objects stored in the heap), and the properties of the objects can be changed arbitrarily.

const o = {
	a: 1
}

const a = [2, 3, 4]


o.b = 2 // 可扩展

o.c = 4

delete o.c // 可删除

o.a = 3 // 可修改

 
a.push(5) // 可扩展

a.pop() // 可删除

a[0] = 3 // 可修改

 
console.log(o) // {a: 3, b: 2}

console.log(a) // [3, 3, 5]

Therefore, the const keyword cannot define a real constant object. The real constant object should be: non-extensible, non-deletable, and non-modifiable.

To do this, we need the help of a function.

Implement constant objects

Object.freezeThe method can freeze an object. Freezing means that the object cannot be expanded, deleted, or modified, and the enumerability, configurability, and writability of the existing properties of the object cannot be modified. This method modifies the original object and returns it. (0 0 0)

Object.isFrozen(obj)Returns whether obj is frozen.

const o = { a:1 }

Object.freeze(o)

 

Guess you like

Origin blog.csdn.net/Mr_linjw/article/details/113931835