javascript - 在javascript中创建不可变对象(immutable对象)

标签 javascript immutability

我有一个从 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/

相关文章:

javascript - 如何在 Web 组件中展平/消除属性更改回调

javascript - 使用 google-map api 仅使用确切位置填充文本框

javascript - 如何用html在面板上制作幻灯片?

Javascript:使用 reduce() 将频率转换为百分比?

immutability - ReactJS:React 中不变性助手的实际用途是什么?

types - OCaml 可变变体类型

c# - 不可变类型是否适用于此缓存问题

javascript - 指令链接函数中的 "Scope"是根作用域,而不是指令作用域

Python 字符串引用

scala - 使用 ZipInputStreams 和 ZipOutpuStreams 时如何避免 Scala 中的可变变量?