[JS] – How do you make an object immutable?

For do this you can use the “freeze” method that has in the javascript Objects. This method not only allow the properties of the object to be changed. If your object has an attribute that holds another object, this other object can already be changed.

Example:

class MyObject {
    constructor(date, quantity, value) {
        this._date = date; // Date Object
        this._quantity = quantity; // integer
        this._value = value; //float
        Object.freeze(this);
    }
}

The date object above can be changed if you are send a Date object as param of this method. However, the quantity and value will be  immutables values.

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s