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?
4 Answers
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.
Comments
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

{}