What is `Object.seal()` for?
Topics
JAVASCRIPT
在GitHub上编辑
TL;DR
Object.seal()
is used to prevent new properties from being added to an object and to mark all existing properties as non-configurable. This means you can still modify the values of existing properties, but you cannot delete them or add new ones.
const obj = { name: 'John' };Object.seal(obj);obj.name = 'Jane'; // Allowedobj.age = 30; // Not alloweddelete obj.name; // Not allowed
What is Object.seal()
for?
Object.seal()
is a method in JavaScript that seals an object, preventing new properties from being added to it and marking all existing properties as non-configurable. This means that while you can still modify the values of existing properties, you cannot delete them or add new properties.
Syntax
Object.seal(obj);
obj
: The object to be sealed.
Behavior
- Preventing new properties: Once an object is sealed, you cannot add new properties to it.
- Non-configurable properties: All existing properties become non-configurable, meaning you cannot delete them or change their property descriptors (e.g., making them non-writable).
- Modifiable values: You can still change the values of existing properties as long as they are writable.
Example
const person = {name: 'Alice',age: 25,};Object.seal(person);person.name = 'Bob'; // Allowedperson.age = 30; // Allowedperson.gender = 'female'; // Not allowed, throws an error in strict modedelete person.name; // Not allowed, throws an error in strict modeconsole.log(person); // { name: 'Bob', age: 30 }
Use cases
- Data integrity: Ensuring that an object structure remains unchanged, which can be useful in scenarios where the object represents a fixed schema.
- Security: Preventing accidental or malicious modifications to an object, especially in shared or global contexts.
Checking if an object is sealed
You can check if an object is sealed using the Object.isSealed()
method.
const obj = { name: 'John' };Object.seal(obj);console.log(Object.isSealed(obj)); // true