Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Object.Freeze Javascript [duplicate]

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)
like image 925
Johnson Avatar asked Nov 27 '17 13:11

Johnson


2 Answers

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)
like image 144
Bamieh Avatar answered Sep 23 '22 00:09

Bamieh


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.

like image 36
Kara Brightwell Avatar answered Sep 25 '22 00:09

Kara Brightwell