When I define a constant B = constant A and change one of the properties of constant B the property of constant A is also modified?

Asked

Viewed 29 times

0

const a = new Map();

const construct = {
    nome: 'Nome',
    alguma: 'coisa'
}

a.set('Chave', construct);

const b = a.get('Chave');

b.alguma = 'outraCoisa'

console.log(a) // Mostra Map(1) { 'Chave' => { nome: 'Nome', alguma: 'outraCoisa' } }

There’s not exactly a problem, but I don’t know why this is happening and I also don’t know the right term to google and understand better, so if anyone can give me a brief explanation I would be very grateful

1 answer

1


This is because a is pointing to an object, but it is not the object itself, it is only a reference to it, as a residential address is in relation to a residence. When you do it for example b = a makes these two references point to the same object and therefore everything you modify in the object through one of these references is reflected when accessing the object by the other.

This is indirect and access to an object through its reference.

That is why I still think it is important to know C, which gives the concept of pointers, which is not found in these more fashionable languages, and are basically references but lower level, without abstracting too much the concept not to give the impression that the object and the reference are the same thing.

Browser other questions tagged

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