How can I give an Object.Freeze on just one object?
Here's the example below where I create a
, I replicate a
in b
, freeze the b
, and try to re-assign a value to a
. But it is no longer possible. Why? How do I do freeze
on just one object?
Thank you!
let a = { "teste" : [1,2,3] }
// I want 'b' freezed
const b = a;
Object.freeze(b);
a.teste = [4,5,6]
console.log(a)
I believe you're misunderstanding the concept of references in javascript. Objects are referenced in javascript, so when you do
const b = a;
basically you are assigning b
a value of the reference a
, in order to get your code to work, and actually "replicate" like you intend, you need to clone the object not pass a reference.
You can use Object.assign({}, ...)
to clone an object into a new one. (notice that its not deep cloning but it should get you going)
let a = { "teste" : [1,2,3] }
// I want 'b' freezed
const b = Object.assign({}, a);
Object.freeze(b);
a.teste = [4,5,6]
console.log(a)
Objects in Javascript are passed by reference, so in your example, the variables a
and b
refer to the same object. Object.freeze
works on the object itself, not the reference, so there's no difference whether you refer to it using a
or b
. This is the same as if you'd just set a property:
let a = { "test" : [1,2,3] }
const b = a;
b.test = [4,5,6]
console.log(a)
If you want to freeze or modify b
without affecting a
, you'll need to clone it first. One way of doing this is using Object.assign
:
let a = { "test" : [1,2,3] }
const b = Object.assign({}, a);
Object.freeze(b);
a.test = [4,5,6]
console.log(a)
This works by copying all of a
's properties to an empty object, then assigning that to b
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With