Does Object.freeze(obj) actually freezes an Object in JS?

Arun Rajeevan
1 min readOct 26, 2018

--

Objects created using the new keyword are mutable. So, you can actually re-assign a method:
Even worse, objects created using the new keyword inherit the prototype of the class that was used to create them. So, changes to a class’ prototype affect all objects created from that class — even if a change is made after the object was created!

The Object.freeze() method freezes an object.(as per the definition)
A frozen object can no longer be changed; (we hope so atleast)
Freezing an object prevents new properties from being added to it, existing properties from being removed, prevents changing the enumerability, configurability, or writability of existing properties, and prevents the values of existing properties from being changed.(agreed)
In addition, freezing an object also prevents its prototype from being changed. freeze() returns the same object that was passed in.

What about:

  1. Nested objects
  2. Properties of parent prototypes.

Note : Values that are objects can still be modified, unless they are also frozen. It means nested objects are not frozen.

Note: Properties can still be added to the prototype even though it is frozen.

Example:

function test(){
this.d=10;
this.jk={ab:90};
}

const obj = new test();

Object.freeze(obj);

obj.jk.ab = 99;

test.prototype.ok = 70;

console.log(obj.ok);
console.log(obj.jk.ab);

Output
70
99

--

--

No responses yet