By default, objects in JavaScript are mutable. We can change the original values (strings, numbers, etc.) and objects. Let's take a look at this object:
Let obj = { ten, obj: { "mutable object" }}
You can easily change it by:
5"changed! " / / {// num:5,// obj: {// content: "changed!" // }// }
It's very clear, isn't it? So, what can we do to make the object immutable?
1, let us try const
!
It's a good try, but it doesn't work. If you try, you'll find that this approach simply doesn't work. The const
keyword simply modifies the link between a variable name and its value, not the actual value. You can still change both the const
original values and objects in the object as you did above. For example:
Constobj ={num:Ten, obj: {content:"mutable Object"}} obj.num=5; Obj.obj= {content:"changed!"} console.log (obj); // {//Num:5,//obj: {//content: "changed!"// }// }
2, continue to try: Object.freeze ().
Object method to achieve our purpose: Object.freeze ()
. This method makes the original property of the object immutable. We apply this method to our original obj
object:
5"changed! " / / {// num:10,// obj: {// content: "changed!" // }// }
The result is a little better later than the original attempt, the raw value is now fixed and cannot be changed, but we can still change the nested object.
3. Final Solution
To make the object completely immutable, we also need freeze()
all the nested objects. For example:
function Deepfreeze (obj) { var propnames = object.getownpropertynames (obj); Propnames.foreach (function (name) { var prop = Obj[name]; if (typeof'object'null) { deepfreeze (prop); } }); return object.freeze (obj);}
Using this function, we can now create a completely immutable object:
5"changed! " / / {// num:10,// obj: {// Content: "mutable object"// }// }
Immutable objects in JavaScript (immutable Objects)