La différence entre le gel superficiel et le gel profond réside dans la manière dont le comportement de gel est appliqué aux objets imbriqués. Voici une répartition des deux 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 |
---|---|---|
Scope | 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. |
Gel peu profond :
Congélation profonde :
Pour gérer les références cycliques, vous pouvez maintenir un WeakSet d'objets visités :
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" } }
Cela empêche la récursion infinie pour les références cycliques.
Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!