JavaScript(JS) object method - seal

h‮ptt‬s://www.theitroad.com

The seal() method is a built-in method of the JavaScript Object constructor. It seals an object, preventing new properties from being added to the object and making all existing properties non-configurable. This means that you cannot delete or reconfigure any existing properties of the object, but you can still modify their values.

Here's the syntax:

Object.seal(obj)

where obj is the object to seal. This method takes only one argument, which is the object to seal.

Here's an example that shows how to use the seal() method:

const myObj = { prop1: "value1", prop2: "value2" };
console.log(Object.isSealed(myObj)); // false

Object.seal(myObj);
console.log(Object.isSealed(myObj)); // true

myObj.prop1 = "new value";
console.log(myObj); // { prop1: "new value", prop2: "value2" }

delete myObj.prop2;
console.log(myObj); // { prop1: "new value", prop2: "value2" }

Object.defineProperty(myObj, "prop3", { value: "value3" });
console.log(myObj); // { prop1: "new value", prop2: "value2", prop3: "value3" }

In this example, we create an object myObj with two properties prop1 and prop2. We use the isSealed() method to check whether the object is sealed. Since the object is not sealed, isSealed() returns false.

Next, we use the Object.seal() method to seal the object. We then use the isSealed() method again to check whether the object is sealed. Since we have sealed the object, isSealed() now returns true.

Finally, we try to modify an existing property prop1, delete an existing property prop2, and add a new property prop3 to the object using the Object.defineProperty() method. The modification of prop1 is successful, but the deletion of prop2 and the addition of prop3 are not allowed since the object is sealed. When we log the value of myObj, we see that it still contains all three properties, but the prop2 property is not deleted, and the prop3 property is not added.

The seal() method is useful for making an object non-extensible and non-configurable. If an object is sealed, you cannot add new properties to it, and you cannot delete or reconfigure its existing properties. However, you can still modify their values.