Preventing Modifications to Objects in JavaScript
For certain objects preventing modification is very important. For example, with error message ids. In my last post I talked about patterns to prevent duplicates, this post focuses on preventing any modifications to an object once constructed.
Firstly, to prevent reassignment (generally less important) just use const:
const errorMessageIds = {};
Though it is the modification of the object keys and values that is the main concern. Object.seal will make the object read only except for property values which can be edited:
const obj = { property1: 'value1', property2: 'value2', property3: 'value3' }; const sealedObj = Object.seal(obj); // Errors are only ignored for demonstration purposes. try { delete sealedObj.property1; } catch (e) { console.log(e); } // TypeError: Cannot delete property 'property1' of #<object> .... try { sealedObj.property4 = 'value4'; } catch (e) { console.log(e); } // TypeError: Cannot add property property4, object is not extensible sealedObj.property3 = 'value3 EDITED'; console.info(sealedObj); // { property1: 'value2', // property2: 'value2', // property3: 'value3 EDITED' }
Object.freeze does the same, but does not allow properties to be edited. Which is why this one will be used in almost all cases of making an object immutable:
const frozenObj = Object.freeze(obj); try { frozenObj.property1 = 'value2'; } catch (e) { console.log(e); } // TypeError: Cannot assign to read only property 'property1' of object '#<object>' ...
Github Location https://github.com/Jacob-Friesen/obscurejs/blob/master/2018/lockObject.js







