How to prevent modification of object in JavaScript ?.


ECMAScript 5 has introduced several methods to prevent modification of object. Those preventive measures ensures that no one, accidentally or otherwise change functionality of object.

There are 3 levels of preventive methods

1) Prevent Extensions

In this level, one cannot add any new properties or methods but can access existing properties or methods. Here there is an ability to delete the respective object. Object.preventExtensions() is the method used to accomplish this task. It prevents any new properties from ever being added to the object.

Example

Live Demo

<html>
<body>
<script>
   var object1 = {
      prop1: 1
   };
   Object.preventExtensions(object1);
   delete object1.prop1 // value got deleted
   try {
      Object.defineProperty(object1, 'prop2', {
      value: 2
   });
   } catch (err) {
   document.write(err);
   }
   document.write("</br>");
   document.write(object1.prop1);
</script>
</body>
</html>

Output

TypeError: Cannot define property prop2, object is not extensible
undefined // deleted so undefined

2) Seal

It is same as preventing extensions, in addition it doesn't allow to delete existing properties or methods. To accomplish this task Object.seal() method is used.

Example

Live Demo

<html>
<body>
<script>
   var object1 = {
      prop1: 1
   };
   Object.seal(object1);
   object1.prop1 = 2;                 // value got changed
   delete object1.prop1;
   try {
      Object.defineProperty(object1, 'prop2', {
      value: 2
   });
   } catch (err) {
      document.write(err);
   }
   document.write("</br>");
   document.write(object1.prop1); // it gives value as 2 because of seal.
</script>
</body>
</html>

Output

TypeError: Cannot define property prop2, object is not extensible
2  // because of seal the value can't be deleated but got updated

3) Freeze

In addition to seal's functionality, freeze doesn't allow even to access the existing properties. To freeze an object we use Object.freeze() method. It can also make an object immutable.

Example

Live Demo

<html>
<body>
<script>
   var object1 = {
      prop1: 1
   };
   Object.freeze(object1);
   object1.prop1 = 2;          //  value got updated
   delete object1.prop1;        // value got deleted
   try {
      Object.defineProperty(object1, 'prop2', {
      value: 2
   });
   } catch (err) {
      document.write(err);
   }
   document.write("</br>");
   document.write(object1.prop1);  // it gives 1 as output despite value updated to 2
</script>
</body>
</html>

Output

TypeError: Cannot define property prop2, object is not extensible
1 // because of freeze the value won't get delete and won't get update. 
raja
Published on 13-Jun-2019 16:36:37
Advertisements