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
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 .
thefourtheye
source share