Object.Reeze Javascript

Asked

Viewed 73 times

1

How can I give a Object.freeze in just one object?

Follow example below where I create a, replicatic a in b, freezo the b, and I try to re-assign a value to a. But it’s no longer possible. Why? How do I 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)

1 answer

1


The values of an object are "references", so you don’t freeze to "variable" in itself, but rather the object and by setting it into another variable you are actually not copying, but yes "referencing", for example:

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

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

y.baz.bar = 400;

console.log(x);

See that when changing y.baz.bar and on display x (and not y) was shown 400, which was previously set out in y, this because you do not "clone" the values, but in fact is referenced, some other languages have similar behavior.

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

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);

  • 1

    Perfect guy, Thank You!! Saved my ass!

Browser other questions tagged

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