Reputation: 398
If you have a javascript variable that is an object and you make a new variable equal the the first variable, does it create a new instance of the object, or do they both reference the same object?
Upvotes: 2
Views: 218
Reputation: 76
Both will refer to the same object. If you want to create a new instance:
var Person = function() {
this.eyes = 2,
this.hands = 2
};
var bob = new Person();
var sam = new Person();
Those two are different objects.
Here is the answer: when you create an object and then assign it to another it will refer to the same object.
Here is an example:
var hacker = {
name : 'Mr',
lastname : 'Robot'
};
console.log(hacker.name + '.' + hacker.lastname);
// Output Mr.Robot
// This variable is reference to hackers object
var anotherPerson = hacker;
console.log(anotherPerson.name + '.' + anotherPerson.lastname);
// Output Mr.Robot
// These will change hacker object name and lastname
anotherPerson.name = 'Elliot';
anotherPerson.lastname = 'Alderson';
console.log(anotherPerson.name + ' ' + anotherPerson.lastname);
// Output "Elliot Alderson"
// After it if you try to log object hacker name and lastname it would be:
console.log(hacker.name + '.' + hacker.lastname);
// Output "Elliot Alderson"
You can check the link here and play with it. It is not to complicated. JSBIN Object Hacker
Upvotes: 1
Reputation: 1670
Object Reference explained!
Look the image for better understanding. When you create an object, suppose s1
it is having just a reference in the memory heap and now when you create another object say s2
and say s1 = s2
that means both the objects are actually pointing to the same reference. Hence when you alter either of them, both change.
Upvotes: 1
Reputation: 23870
They always reference the same object. We can see that by trying the following:
var x = {foo:11};
var y = x;
y.foo = 42;
console.log(x.foo);
// will print 42, not 11
Upvotes: 3
Reputation: 5556
If you mean something like this
var a = { foo: "foo" };
var b = a;
then yes. They reference the same object.
Upvotes: 0