How to freeze an Object in JavaScript?

JavascriptObject Oriented ProgrammingProgramming

In the Real time world javascript doesn't have traditional classes as seen in other languages. It has objects and constructors. Object.freeze() is one among many constructor methods helps to freeze an object.

Freezing an object does not allow new properties to be added to the object and also prevents the object from changing its own properties. Object.freeze() will always try to preserve the enumerability, configurability, writability and the prototype of the object. It won't create a frozen copy.

Applications

1) freeze() is used for freezing objects and arrays.

2) freeze() is used to make an object immutable.

Syntax

Object.freeze(obj)

Example

Live Demo

<html>
<body>
<script>
// an object is created and a value is assigned
   var myObj1 = {
                prop1: 'freezed values can not be changed'
                };

// the created object is freezed
   var myObj2 = Object.freeze(myObj1);

// property of the frozen object is updated
   myObj2.prop1 = 'change the freezed value';

// Displaying the properties of the frozen object -->
   document.write(myObj2.prop1);

</script>
</body>
</html>

Output
freezed values can not be changed

raja
Published on 06-Jun-2019 15:12:54
Advertisements