Perbezaan antara pembekuan cetek dan pembekuan dalam terletak pada cara tingkah laku pembekuan digunakan pada objek bersarang. Berikut ialah pecahan dua konsep:
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. |
Pembekuan Cetek:
Pembekuan Dalam:
Untuk mengendalikan rujukan kitaran, anda boleh mengekalkan WeakSet objek yang dilawati:
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" } }
Ini menghalang rekursi tak terhingga untuk rujukan kitaran.
Atas ialah kandungan terperinci Objek JavaScript - Pembekuan cetek lwn pembekuan dalam. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!