📅  最后修改于: 2023-12-03 15:01:38.363000             🧑  作者: Mango
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.
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);
Once an object is sealed using Object.seal()
, the following restrictions are enforced on the object:
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.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.
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
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.