The difference between shallow freeze and deep freeze lies in how the freezing behavior is applied to nested objects. Here’s a breakdown of the two concepts:
const shallowObject = { name: "Alice", details: { age: 25, city: "New York" }, }; Object.freeze(shallowObject); // Top-level properties are immutable shallowObject.name = "Bob"; // Ignored shallowObject.newProp = "test"; // Ignored // Nested objects are still mutable shallowObject.details.age = 30; // Allowed console.log(shallowObject); // Output: { name: "Alice", details: { age: 30, city: "New York" } }
const deepObject = { name: "Alice", details: { age: 25, city: "New York" }, }; // Deep freeze function function deepFreeze(object) { const propertyNames = Object.getOwnPropertyNames(object); for (const name of propertyNames) { const value = object[name]; if (value && typeof value === 'object') { deepFreeze(value); // Recursively freeze } } return Object.freeze(object); } deepFreeze(deepObject); // Neither top-level nor nested properties can be changed deepObject.name = "Bob"; // Ignored deepObject.details.age = 30; // Ignored console.log(deepObject); // Output: { name: "Alice", details: { age: 25, city: "New York" } }
Feature | Shallow Freeze | Deep Freeze | |||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
|
Only freezes top-level properties. | Freezes top-level and nested objects. | |||||||||||||||
Nested Object Mutability | Mutable. | Immutable. | |||||||||||||||
Implementation | Object.freeze(object). | Custom recursive function with Object.freeze(). | |||||||||||||||
Example Mutation | Modifications to nested objects are allowed. | No modifications allowed at any level. |
Shallow Freeze:
Deep Freeze:
To handle cyclic references, you can maintain a WeakSet of visited objects:
const shallowObject = { name: "Alice", details: { age: 25, city: "New York" }, }; Object.freeze(shallowObject); // Top-level properties are immutable shallowObject.name = "Bob"; // Ignored shallowObject.newProp = "test"; // Ignored // Nested objects are still mutable shallowObject.details.age = 30; // Allowed console.log(shallowObject); // Output: { name: "Alice", details: { age: 30, city: "New York" } }
This prevents infinite recursion for cyclic references.
The above is the detailed content of JavaScript Object - Shallow freeze vs Deep freeze. For more information, please follow other related articles on the PHP Chinese website!