How to make a constant object in JavaScript

4

How do I declare a constant object in JavaScript? For example:

/* meu código */
object_teste = {valor:5}

/* console navegador */
object_teste.valor=10;
console.log(object_teste.valor) // aqui ele me retorna 10 ao invés de 5 

How to leave this value constant? As if it were a constant variable but in this case an object.

    
asked by anonymous 12.03.2014 / 20:57

2 answers

7

I think something like Object.freeze(object_teste); solves your problem.

This function "freezes" the object, leaving it immutable.

I think the script below will help with recursion in case you need to freeze sub objects:

Object.prototype.recursiveFreeze = function() {

    for(var index in Object.freeze(this)) {

        if(typeof this[index] == 'object') {

            this.recursiveFreeze.call(Object.freeze(this[index]));

        }

    }

}

// Uso:

myObject.recursiveFreeze();
    
12.03.2014 / 21:00
5

You can use Object.freeze ()

Object.freeze(object_teste);

Example

    
12.03.2014 / 21:02