How to deep-freeze o...
How to deep-freeze o...
To deep-freeze an object in JavaScript means to recursively apply Object.freeze()
to an object and all objects it references, directly or indirectly, so that the entire structure becomes immutable. This is necessary because Object.freeze()
is shallow and only freezes the object's immediate properties. If the object has properties that are objects themselves, these nested objects can still be modified unless they are also frozen.
Here's a function that demonstrates how to deep-freeze an object in JavaScript:
function deepFreeze(object) {
// Retrieve the property names defined on object
const propNames = Object.getOwnPropertyNames(object);
// Freeze properties before freezing self
for (const name of propNames) {
const value = object[name];
// If value is an object and not already frozen, recursively call deepFreeze
if (value && typeof value === 'object' && !Object.isFrozen(value)) {
deepFreeze(value);
}
}
// Freeze self (no-op if already frozen)
return Object.freeze(object);
}
To use this function, you would call it with the object you want to freeze:
const myObject = {
internal: {
a: null
}
};
deepFreeze(myObject);
// Now myObject is deeply frozen, and attempts to modify it will throw errors (in strict mode)
myObject.internal.a = 'someValue'; // TypeError: Cannot assign to read only property 'a' of object '#<Object>'
This function works by first freezing the properties of the object, which might themselves be objects, and then freezing the object itself. It uses Object.getOwnPropertyNames()
to find all properties (including non-enumerable ones) and then recursively applies Object.freeze()
to each property that is an object. Finally, it freezes the original ob...
expert
Gợi ý câu hỏi phỏng vấn
Chưa có bình luận nào