Why does it work? Object Links in Javascript

Finally, I was curious to know why javascript does its voodoo magic to find out why not all object references are created equal.

For example:

var a, b, c, d; a = 100; b = a; c = {}; d = c; b = 10; de = 'f'; console.log(a, b); // outputs 100, 10 console.log(c, d); // outputs object => e = 'f', object => e = 'f' 

If all the variables in javascript are objects, then what makes the use case with c and d explicitly expressed as Object , how does a and b differ as Number ? Or, why are c and d related to each other and not a and b ?

+6
source share
3 answers

All variables in JavaScript are not objects. There are also native types.

c and d not related to each other. They point to the same object reference. If you reassign d to something else, it will not affect c .

 var c = {}; var d = c; d = { foo: "bar" }; c === d // false 

However, if you want to change the object referenced by c or d , it will change the same object, since c and d both refer to the same object as in your example.

+8
source

It seems to me that the difference is in b , you reassign the variable to a new object / value, and with d you change the existing object.

+3
source

The value of a assigned by b is the number. The value assigned from c to d is an object reference.

 var a, b, c, d; a = 100; // a has value 100, a number b = a; // b has value 100, a number c = {}; // c has value p, a reference to some object P d = c; // d has value p, a reference to P b = 10; // b has value 10, a number de = 'f'; // Pe has value 'f', a string 
+2
source

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


All Articles