-
Notifications
You must be signed in to change notification settings - Fork 59
Description
Object.freeze(obj) is very handy but it only operates on the object’s immediate properties.
The result of calling Object.freeze(object) only applies to the immediate properties of object itself and will prevent future property addition, removal or value re-assignment operations only on object. If the value of those properties are objects themselves, those objects are not frozen and may be the target of property addition, removal or value re-assignment operations.
The MDN article provides an example method:
function deepFreeze(object) {
// Retrieve the property names defined on object
const propNames = Reflect.ownKeys(object);
// Freeze properties before freezing self
for (const name of propNames) {
const value = object[name];
if ((value && typeof value === "object") || typeof value === "function") {
deepFreeze(value);
}
}
return Object.freeze(object);
}Why might freezing be important?
You could freeze sensitive objects like It can't really protects against that, but it might be beneficial for the developer to freeze objects not meant to be changed.pricingObject or checkoutConfig etc. to prevent tampering by browser extensions or crafty users.