在 javascript 中创建不可变对象
Create immutable object in javascript
我有一个例程,我从 api 接收一些数据。我想将此数据存储在一个对象中,但在那之后我想 "lock" 这个对象,并且在那之后不允许对属性或它们的值进行任何更改。那可能吗? (如果可能,只使用 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
没有。没有好的方法来强制执行 const
-ness 是 ES5。
对于不可变对象,我们可以使用以下方法
Object.freeze()
- 要在更新对象时强制对象不变性,请确保
- 使用
Object.assign({},a,{foo:'bar'})
而不是a.foo='bar'
- 我们可以使用
spread(...)
运算符。
参见示例:
var person={name:'pavan',age:26}
var newPerson={...person,name:'raju'}
console.log(newPerson ===person) //false
console.log(person) //{name:'pavan',age:26}
console.log(newPerson) //{name:'raju',age:26}
我有一个例程,我从 api 接收一些数据。我想将此数据存储在一个对象中,但在那之后我想 "lock" 这个对象,并且在那之后不允许对属性或它们的值进行任何更改。那可能吗? (如果可能,只使用 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
没有。没有好的方法来强制执行 const
-ness 是 ES5。
对于不可变对象,我们可以使用以下方法
Object.freeze()
- 要在更新对象时强制对象不变性,请确保
- 使用
Object.assign({},a,{foo:'bar'})
而不是a.foo='bar'
- 我们可以使用
spread(...)
运算符。
参见示例:
var person={name:'pavan',age:26}
var newPerson={...person,name:'raju'}
console.log(newPerson ===person) //false
console.log(person) //{name:'pavan',age:26}
console.log(newPerson) //{name:'raju',age:26}