Object.freeze Javascript

1

How can I get a Object.freeze on just one object?

Here's the example below where I create a , replicate a to b , freezo b , and try to re-assign a value to a . But it is no longer possible. Because? How do I do Freeze on just one object?

Thank you!

let a = { "teste" : [1,2,3] }

// Quero 'b' freezado
const b = a;
Object.freeze(b);

a.teste = [4,5,6]

// 'a' não foi freezado e mesmo assim não consigo alterar o valor dele
console.log(a)
    
asked by anonymous 27.11.2017 / 14:43

1 answer

1

The values of an object are "references" , so you do not freeze the "variable" itself, but rather the object and set it to another variable in the

let x = {
    "foo": {
        "bar": 1
    }
};

let y = {
    "baz": x.foo
};

y.baz.bar = 400;

console.log(x);

Note that changing y.baz.bar and displaying x (not y ) 400 , which was previously set to y , is displayed because you do not "clone" the values, but in% truth is referenced, some other languages have similar behavior.

Then Object.freeze will freeze the reference, if you want to copy the values from one object to another (clone) use Object.assign , like this:

var a = { ... };
var b = Object.assign({}, a);

See a test:

let a = { "teste" : [1,2,3] }

// Quero 'b' freezado
const b = Object.assign({}, a);
Object.freeze(b);

a.teste = [4,5,6];

console.log("a:", a);
console.log("b:", b);
    
27.11.2017 / 15:07