How to deep-freeze object in JavaScript?
How to deep-freeze object in JavaScript?
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
Can you describe the main difference between a .forEach loop and a .map() loop and why you would pick one versus the other?
Xem chi tiếtCan you give an example for destructuring an object or an array in ES6?
Xem chi tiếtCan you give an example of a curry function and why this syntax offers an advantage?
Xem chi tiếtĐăng nhập để tham gia thảo luận cùng mọi người.
Chưa có bình luận nào
Hãy là người đầu tiên chia sẻ suy nghĩ của bạn.