浅冻结和深度冻结之间的区别在于如何将冻结行为应用于嵌套对象。以下是这两个概念的细分:
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中文网其他相关文章!