I've finally been curious enough to find out why javascript does its voodoo magic to learn why not all object references are created equal.
Given the example:
var a, b, c, d;
a = 100; b = a;
c = {}; d = c;
b = 10; d.e = 'f';
console.log(a, b); // outputs 100, 10
console.log(c, d); // outputs object => e = 'f', object => e = 'f'
If all variables in javascript are objects, then what makes the use case with c
and d
cast explicitly as an Object
so different than defining a
and b
as Number
? Or, why will c
and d
be linked to one another, and not a
and b
?
Objects in JavaScript are passed by reference. When more than one variable is set to store either an object , array or function , those variables will point to the same allocated space in the memory.
You use an object reference variable to create, manage, and delete objects. It has the data type of a class and, like other variables, is a named area in storage. However, unlike other variables, the value stored in the area is not the object itself but a 4-byte pointer to the object data, called an object reference.
In Pass by Reference, a function is called by directly passing the reference/address of the variable as the argument. Changing the argument inside the function affects the variable passed from outside the function. In Javascript objects and arrays are passed by reference.
In JavaScript, the this keyword refers to an object. Which object depends on how this is being invoked (used or called). The this keyword refers to different objects depending on how it is used: In an object method, this refers to the object.
All variables in JavaScript are not objects. There are native types as well.
c
and d
are not linked to one another. They are pointing to the same object reference. If you were to reassign d
to something else, it will not affect c
.
var c = {};
var d = c;
d = { foo: "bar" };
c === d // false
However, if you were to modify the object being referenced by c
or d
, it will modify the same object since c
and d
are both referring to the same object as in your example.
It looks to me that the difference is with b
, you're reassigning the variable to a new object/value, while with d
, you're modifying the existing object.
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