Object.prototype.freeze
Object.freeze()
can easily make an object un-editable. After you freeze an object you can not touch it’s properties. Deleting or changing frozen objects doesn’t throw an error but doen’t take effect either.
var o = {val: 1}; Object.freeze(o); o.val = 2; // this will not make any change to `o` Object.isFrozen(o); // true o.val === 1; // true
Why do we need to unfreeze an object?
It seems strange to freeze an object at first place and then try to unfreeze it afterwards. But in some situations you don’t have control over all codebase and you face frozen objects that and you want to change that object for reasons like debugging, testing, etc.
For example I was writing Jasmine tests for my WinJS application and Jasmine’s spy()
method was not able spy on frozen WinJS objects methods. Windows doesn’t allow developers to touch WinJS code.
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.
How to unfreeze?
Basically you can not unfreeze an object using JavaScript language methods. There is no Object.unfreeze()
Method. Unfortunately a “copy” of the frozen Object is frozen too:
var o = {val: 1}; Object.freeze(o); var _o = o; Object.isFrozen(_o) // true
Solution is to clone the frozen object and work with that object instead. By creating a brand new object and filling all properties from original(frozen) object to it we get equal object that is not frozen.
var obj = {val: 1, max: 10}; Object.freeze(obj) var _obj = {}; for (var prop in obj) { if(obj.hasOwnProperty(prop)) { _obj[prop] = obj[prop]; } } Object.isFrozen(_obj); //false //now you can replace original object with the unfrozen one obj = _obj;