浅いフリーズと深いフリーズの違いは、フリーズ動作がネストされたオブジェクトにどのように適用されるかにあります。 2 つの概念の内訳は次のとおりです。
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. |
シャローフリーズ:
ディープフリーズ:
循環参照を処理するには、訪問したオブジェクトの WeakSet を維持できます。
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" } }
これにより、循環参照の無限再帰が防止されます。
以上がJavaScript オブジェクト - 浅いフリーズと深いフリーズの詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。