How to thaw / thaw a frozen object in Javascript?

Could you show me how to defrost a frozen object in Javascript so that I can change its properties?

var pizza = { name: 'Peri Peri', Topping: 'Prawn' }; Object.freeze(pizza); // Can't change the name of the object because it frozen pizza.name = 'Hawaiian'; 
+7
javascript object
source share
2 answers

Technically, Object.freeze makes an object immutable. Quote from this page,

Nothing can be added or removed from the set of properties of a frozen object. Any attempt to do this will fail, either quietly or by throwing a TypeError exception (most often, but not exclusively, when in strict mode).

Values ​​cannot be changed for data properties. The properties of accessories (getters and setters) work the same way (and yet give the illusion that you are changing the value). Note that values ​​that are objects may still be changed if they are not frozen.

So, the only way this can be done is to clone an object

 var pizza = { name: 'Peri Peri', Topping: 'Prawn' }; Object.freeze(pizza); pizza.name = 'Hawaiian'; console.log(pizza); // { name: 'Peri Peri', Topping: 'Prawn' } pizza = JSON.parse(JSON.stringify(pizza)); // Clones the object pizza.name = 'Hawaiian'; console.log(pizza); // { name: 'Hawaiian', Topping: 'Prawn' } 

Note 1: In strict mode, it CANNOT fail and cause an error instead.

 "use strict"; ... ... pizza.name = 'Hawaiian'; ^ TypeError: Cannot assign to read only property 'name' of #<Object> 

Note 2: If your object has methods, then the JSON.stringify approach JSON.stringify NOT receive them. You can learn more about the proper cloning of objects in these three questions .

+12
source share

You cannot: Source

Freezing an object is the ultimate form of locking. Once an object has been frozen, it cannot be thawed - and it cannot be a manner. This is the best way to make sure your objects stay exactly the same as you left them for an indefinite period.

From a similar question here: https://stackoverflow.com/a/316618/

+2
source share

All Articles