16

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';
thefourtheye
  • 233,700
  • 52
  • 457
  • 497
Toan Nguyen
  • 11,263
  • 5
  • 43
  • 59

2 Answers2

17

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.

Community
  • 1
  • 1
thefourtheye
  • 233,700
  • 52
  • 457
  • 497
3

You can't: Source

Freezing an object is the ultimate form of lock-down. Once an object has been frozen it cannot be unfrozen – nor can it be tampered in any manner. This is the best way to make sure that your objects will stay exactly as you left them, indefinitely.

From a similiar question here: https://stackoverflow.com/a/19293418/1420186

Community
  • 1
  • 1
Tony Dinh
  • 6,668
  • 5
  • 39
  • 58