flukeflume
flukeflume

Reputation: 707

Javascript Object Multiple references

Just a (hopefully) quick question to clear something up with how Javascript handles objects. I'm not used to JS so it came as a bit of a surprise, which is why I want to double check!

Say I have an object:

function food(price) {
  this.price = price || 100; 
}

var myFood = new food(100);

And then store this object in two arrays:

var foo = [];
var bar = [];
foo.push(myFood);
bar.push(myFood);

Am I right in thinking that all I'm doing here is storing a REFERENCE to myFood? I'm not creating a COPY of the object? So if I were to, say:

foo[0].price = 50;

Would bar[0].price ALSO == 50, as it stores a reference to myFood, and it is myFood that has actually had its price affected, not foo or bar?

Many thanks in advance! I've seen a few stack overflow threads that mention this issue as part of a wider post, but I just wanted to lay it all out there to make sure! Best regards

Upvotes: 4

Views: 1656

Answers (2)

Alex Wayne
Alex Wayne

Reputation: 187044

You are correct. But it's incredibly easy to just do it and see what happens.

http://jsfiddle.net/67haQ/

You clearly seem to know how it works already, a little playing around for confirmation seems easier than a SO question.

Just sayin'

Upvotes: 2

TheZ
TheZ

Reputation: 3732

Yes, javascript will just push a reference not a copy of the object.

Upvotes: 2

Related Questions