Freezing Javascript Object

Posted By : Prashank Jauhari | 18-Sep-2017

What does freezing mean?

It refers to the process of making a javascript object immuatble. If your are java programmer then you might be familier with final object. i.e object whose values can never be modifed once initilized and we can't even add new properties to these objects.

 

Some time during development we need some objects which are immutable. Below code snippets provide serveral ways to achieve that.

1)

 

As it visible from the above code snippet before frezzing the object via Object.freeze() we are able to mofify the object structure and values but once Object.freeze(a) statement is executed Object became final i.e no modification is allowed.

 

2) Instead calling Object.freeze on each object we can modify the code of javascript constructor to create immutable Object.

 

 

As it is visible from above code we can even modify the constructor code to create object that are final. But what if we want to add some new properties like i tried to add designation to person1 object. We can Modify the above constructor logic as per our needs.

 

Notes: above constructor's code is as follows (in case above code is not readable)

function Person(firstname,lastname){

this.firsname=firstname;

this.lastname=lastname;

return Object.freeze(this);

}

 

3) Problem in above code can be modifed by code snippet below.

 

What if you have chain of constructors?

So in that case first parent constructors intilize there part after that child constructor add there properties? Blindily freezing the object won't be the smart choice because it will forbid child constructor to do there work.

 

For better understanding please refer to below code snippet.

 

As it is visible from above code that Employee constructor is not able to add new values after calling Person's constructor(i.e constructor up the constructor chain). The above problem can be solved by only freezing the object by constructor , if it is the first constructor invoked in the constructor chain. Plesae refer below code snippet.

 

About Author

Author Image
Prashank Jauhari

Prashank is quick learner and passionate about new technologies. He is currently working as Java Developer with knowledge of Spring and Hibernate.

Request for Proposal

Name is required

Comment is required

Sending message..