How to make a constant object in Javascript

Asked

Viewed 405 times

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 constant value? As if it were a constant variable but in this case an object.

  • 2

    Related questions: "How to declare a constant in javascript?" and "How to create an immutable object in Javascript?" (I’m not sure if any of them are duplicates or if they’re just similar questions, so I’m not voting to close)

  • 1

    The question is good and the answers too, but what do you plan to use the frozen object for? If possible, avoid freezing objects. They get more slow, not to mention that Object.freeze does not work in IE8.

  • to declare a use variable var: var object_test = {value:5}, in case you set the object again, if you want a constant, Object.Freeze(your variable);

2 answers

7


I believe something like Object.freeze(object_teste); solve your problem.

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

I believe the script below helps 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();
  • Thanks buddy, it worked out :)

  • @tchicotti, Freeze() does not allow changing values. Diego is correct. +1

  • 4

    Note that if some property is another object, you need to freeze it too, in the nail.

  • @bfavaretto, well noted, if it is your case a recursive function should solve Silvio.

  • @bfavaretto yes truth I’ll have to do that.

  • I’ll edit my answer with something I think will help.

  • Thanks bro, it worked dahora.

Show 2 more comments

5

Browser other questions tagged

You are not signed in. Login or sign up in order to post.