I just stumbled upon Object.freeze() function. It seems to be a pretty good feature but how to make whole object (including nested objects) immutable?
For example I can change innerProp
here:
const obj = { prop: { innerProp: 1 } };
obj.prop.innerProp = 5;
console.log(obj.prop.innerProp); // 5
Is it possible do freeze nested objects too? (ECMAScript 5/6)
function deepFreeze (o) {
Object.freeze(o);
if (o === undefined) {
return o;
}
Object.getOwnPropertyNames(o).forEach(function (prop) {
if (o[prop] !== null
&& (typeof o[prop] === "object" || typeof o[prop] === "function")
&& !Object.isFrozen(o[prop])) {
deepFreeze(o[prop]);
}
});
return o;
};
https://github.com/substack/deep-freeze
It's public domain so you don't have to give credit :D
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With