📜  Javascript Object.seal()(1)

📅  最后修改于: 2023-12-03 15:01:38.363000             🧑  作者: Mango

JavaScript Object.seal()

The Object.seal() method is a powerful tool provided by JavaScript that allows you to prevent new properties from being added to an object, and also prevents the existing properties from being deleted or changed.

Usage

The Object.seal() method can be applied to any object. Here's how you can use it:

const obj = {
  name: "John",
  age: 25
};

Object.seal(obj);
Effect

Once an object is sealed using Object.seal(), the following restrictions are enforced on the object:

  • New properties cannot be added: You cannot add new properties to the sealed object. Any attempt to do so will be ignored or throw an error, depending on whether you are using strict mode.
  • Existing properties cannot be deleted: You cannot delete any existing properties of the sealed object. Any attempt to delete a property will be ignored or throw an error in strict mode.
  • Existing properties cannot be reconfigured: The configurable attribute of the existing properties becomes false. This means you cannot change the attributes of an existing property such as writable or enumerable. However, you can still modify the value of the property.
Example
const obj = {
  name: "John",
  age: 25
};

Object.seal(obj);

obj.age = 30; // Valid, modifies the value of the existing property
obj.gender = "male"; // Ignored, new property cannot be added
delete obj.name; // Ignored, existing property cannot be deleted
Object.defineProperty(obj, 'name', { enumerable: false }); // Throws an error, property attributes cannot be changed

In the above example, after using Object.seal(), we cannot add the gender property, delete the name property, or change the attributes of the name property. However, we can still modify the value of the age property.

Checking if an object is sealed

You can use the Object.isSealed() method to check if an object is sealed. It returns true if the object is sealed; otherwise, it returns false.

const isSealed = Object.isSealed(obj);
console.log(isSealed); // Output: true
Conclusion

The Object.seal() method is a handy tool for controlling the mutability of objects in JavaScript. By sealing an object, you can ensure that it stays in a consistent state, preventing any accidental modifications or unwanted additions or deletions of properties.