Reputation: 301
suppose i have this
var x={}; //x is an address in the memory where object is stored
var z=x; //z=x after execution is equal to z={} right?
now z has nothing to do with x or not related to x after execution so when,
x={name:"Maizere"};
z!=x //true
but, when
x.name="maizere";
alert(z.name)//maizere why?
we are not setting the value of z but x and z relation to x shouldn't exit anymore
actual code:
x={};
y=x;
x.name="maizere";
alert(y.name)//maizere
I really have no knowledge of how this is working .Can anyone explain this in detail please?
Upvotes: 2
Views: 113
Reputation: 173532
After these two statements:
x={};
y=x;
The internal representation is like this:
+---- x
|
{} <--+
|
+---- y
So any changes to x
are reflected in y
:
x.name="maizere";
alert(y.name)//maizere
Updated:
+---- x
|
{name: 'maizere'} <--+
|
+---- y
This goes away once you assign either variable to something else:
x = { name: "Maizere" }
Representation:
{name: 'Maizere'} <------- x
{name: 'maizere'} <------- y
Upvotes: 3
Reputation: 33163
Your initial assumption is wrong; z
is a pointer to the same object as x
.
var x = {};
var z = x;
alert( z === x ); // true
When you do x = { name: "Maizere" };
you're assigning a new object to x
. z
is still pointing to the original object.
x = { name: "Maizere" };
alert( z !== x ); // true
In the latter example you're not creating a new object but changing the original object's property.
var x = {};
var z = x;
x.name = "maizere";
alert( z === x ); // true
A further example of where the confusion might stem from: the bracket syntax creates a new object instead of modifying the original.
var x = { name: "Maizere" };
var y = { name: "Zaimere" };
x = { age: 20 };
y.age = 30;
console.log( x ); // {age: 20} <-- original object is replaced
console.log( y ); // {name: "Zaimere", age: 30} <-- original object is modified
Upvotes: 3