Why is the reference to the object non-zero?

I can not explain the following behavior:

var persona = {nome:"Mario", indirizzo:{citta:"Venezia"}}
var riferimento = persona.indirizzo;
// riferimento ==> {citta: "Venezia"} <-- It is Ok

persona.indirizzo.citta = "Torino";
// riferimento ==> {citta: "Torino"} <-- It is Ok

persona.indirizzo = null;
// riferimento ==> {citta: "Torino"} <-- Why?

persona.indirizzo = undefined;
// riferimento ==> {citta: "Torino"} <-- Why?

I tested this in C # and JavaScript, and I have the same behavior.

Why is my riferimento variable not null or undefined?

+4
source share
3 answers

Because it is a link. This is not an actual object, it is just a kind of "pointer" to the place in memory where the object lives. Consider these two statements:

  • You can have as many references to the same object that you need.
  • When you set the value of a link, you only change the link, not the object.

So when you do this:

persona.indirizzo = null;

, indirizzo. indirizzo - . null. - . riferimento . (: , , "" . //etc -.)

, :

persona.indirizzo.citta = "Torino";
persona.indirizzo = null;

- . , .

+1

persona.indirizzo riferimento {citta: "Venezia"}.

, :

persona.indirizzo.citta = "Torino";

, , , . :

persona.indirizzo = null;

, .

0

In C # (not sure about javascript) the following happens:

var persona = {nome:"Mario", indirizzo:{citta:"Venezia"}}

Creates a new object , however persona.indirizzo is not the object itself, but simply a reference to it (the actual object is somewhere on the stack).

var riferimento = persona.indirizzo;

creates a NEW reference to the object that persona.indirizzo points to.

Due to clearing the link in person, the new link does not change.

0
source

Source: https://habr.com/ru/post/1690022/


All Articles