Immutable Objects with Javascript

We create immutable objects, so that no one can change during the app's lifecycle. By default, all Javascript types, except objects, define immutable values

Now what happen, when you copy an object obj1 into another object obj2, & then when you change/add/remove property from obj1, it also affected original object obj1. E.g :

var obj1 = { a : 5, b :  7 };
var obj2 = obj1;
obj2.a  = 7;
//console.log(obj1); => { a : 7, b : 7}

For overcoming these javascript behaviour or to create Immutable objects which doesn't mutate cloning, we have following ways : -

1. This Simple Hack : -

var obj2 = JSON.parse(JSON.stringify(obj1));

Now,
obj2.a  = 7;
//console.log(obj1); => { a : 5, b : 7}

Using Javascript's defineProperty we can create non configurable and/or hidden properties inside objects. This way we can be sure that a developer can't mess with our code or hide from them info about our structures that they don't have to know about. defineProperty won't throw an error while you're trying to alter the object's properties

3. Object.freeze() Object.seal() 
freeze and seal are basically shorthands for the defineProperty and can both come in handy. Make sure that their compatibility tables meet your needs before you use them. Will throw an error and will save you hours of frustration.


4. Object.assign
It's a new feature in ES5. 
The Object.assign() method is used to copy the values of all enumerable own properties from one or more source objects to a target object. It will return the target object.

var objj2 = Object.assign({}, obj1);



Comments

Popular posts from this blog

What is MQTT protocol & its use

What the hack is Call, bind & apply

What is Provider in Angular Js?