Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to thaw/defrost a frozen object in Javascript? [duplicate]

Could you please show me how to defrost a frozen object in Javascript, so that I will be able to modify its properties?

var pizza = {
    name: 'Peri Peri',
    Topping: 'Prawn'
};

Object.freeze(pizza);

// Can't change the name of the object because it's frozen
pizza.name = 'Hawaiian';
like image 947
Toan Nguyen Avatar asked Feb 27 '14 03:02

Toan Nguyen


People also ask

How do you unfreeze an object in JavaScript?

There is no way to do this, once an object has been frozen there is no way to unfreeze it. This is technically correct as far as mutating the existing object. However, you can copy/clone the existing object and mutate it's properties now.

How can we make an object immutable in JavaScript?

You can freeze (make immutable) an object using the function Object. freeze(obj) . The object passed to the freeze method will become immutable. The freeze() method also returns the same object.

Is JavaScript object immutable?

In JavaScript Arrays and Objects are not immutable. Their values can be changed over time. Both are always passed as a reference and the vast majority of available methods mutate data in place.


1 Answers

Technically, Object.freeze makes an object immutable. Quoting from that page,

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

Values cannot be changed for data properties. Accessor properties (getters and setters) work the same (and still give the illusion that you are changing the value). Note that values that are objects can still be modified, unless they are also frozen.

So, the only way this could be done is, by cloning the 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 will NOT fail silently and throw 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 JSON.stringify approach will NOT get them. You can read more about properly cloning the objects in these three questions.

like image 117
thefourtheye Avatar answered Sep 23 '22 17:09

thefourtheye