在 JavaScript 中使用物件時,控制其可變性對於防止意外變更至關重要。 JavaScript 為此提供了兩種方法:Object.freeze() 和 Object.seal()。了解它們的差異和用例是編寫健全程式碼的關鍵。
Object.freeze() 方法使物件不可變。這意味著:
Object.freeze(obj);
const obj = { name: "Alice", age: 25 }; Object.freeze(obj); obj.age = 30; // Does nothing (strict mode: throws an error) obj.gender = "female"; // Does nothing (strict mode: throws an error) delete obj.name; // Does nothing (strict mode: throws an error) console.log(obj); // { name: "Alice", age: 25 }
使用 Object.isFrozen() 來決定物件是否被凍結:
console.log(Object.isFrozen(obj)); // true
Object.seal() 方法限制物件的修改,但不如 Object.freeze() 嚴格。它允許:
Object.seal(obj);
const obj = { name: "Bob", age: 30 }; Object.seal(obj); obj.age = 35; // Allowed: Existing properties can be modified obj.gender = "male"; // Does nothing (strict mode: throws an error) delete obj.name; // Does nothing (strict mode: throws an error) console.log(obj); // { name: "Bob", age: 35 }
使用 Object.isSealed() 判斷物件是否被密封:
Object.freeze(obj);
Feature | Object.freeze() | Object.seal() |
---|---|---|
Add new properties | Not allowed | Not allowed |
Remove existing properties | Not allowed | Not allowed |
Modify existing properties | Not allowed | Allowed |
Reconfigure property descriptors | Not allowed | Not allowed |
Use case | Immutable objects (constants) | Restrict structure but allow value changes |
const obj = { name: "Alice", age: 25 }; Object.freeze(obj); obj.age = 30; // Does nothing (strict mode: throws an error) obj.gender = "female"; // Does nothing (strict mode: throws an error) delete obj.name; // Does nothing (strict mode: throws an error) console.log(obj); // { name: "Alice", age: 25 }
console.log(Object.isFrozen(obj)); // true
防止與物件可變性的混淆:清楚記錄物件被凍結或密封的時間和原因,以避免在團隊環境中產生誤解。
凍結前密封
以上是掌握 JavaScript 中的 Object.freeze() 和 Object.seal():控制物件可變性的詳細內容。更多資訊請關注PHP中文網其他相關文章!