我有一个从 api 接收一些数据的例程。我想将这些数据存储在一个对象中,但在那之后我想“锁定”这个对象,并且在那之后不允许对属性或它们的值进行任何更改。那可能吗? (如果可能,只使用 ES5)。
最佳答案
如果您希望某个对象不能被修改,您可以使用Object.freeze
。 .
The
Object.freeze()
method freezes an object: that is, prevents new properties from being added to it; prevents existing properties from being removed; and prevents existing properties, or their enumerability, configurability, or writability, from being changed, it also prevents the prototype from being changed. The method returns the object in a frozen state.
如果您只是想防止变量被重新分配,您可以使用 const
(ES6),但请注意:
The const declaration creates a read-only reference to a value. It does not mean the value it holds is immutable, just that the variable identifier cannot be reassigned.
例如,以下是完全有效的
const a = { x: 7 }
a.x = 9
console.log(a.x) // 9
但是,尝试重新分配用 const
声明的变量将抛出 TypeError
:
const a = 5
a = 7
关于javascript - 在javascript中创建不可变对象(immutable对象),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46853278/