Reputation: 9
The problem is: I expect the price of Animals[0] to decrease, but it also decreases the price of Cattypes[0]. How does this happen?
function Cat( name, size, price, colour, food)
{
this.name = name;
this.size = size;
this.price = price;
this.colour = colour;
this.food = food;
}
Cattypes = [];
Cattypes.push(new Cat("Dinky",20,150,"blue","fish"));
Animals = [];
Animals[0].push(Cattypes[0]);
Animals[0].price -= 140;
alert(Cattypes[0].price);
Upvotes: 0
Views: 62
Reputation: 2022
When you pass objects to a function in JavaScript, the reference to this object is passed. Objects are not copied. When you add Cattypes[0]
to your Animals
array, the object is not copied. You're accessing the same object.
Animals[0].price -= 140; // here, Animals[0] is the same as Cattypes[0]
This is the anwser to the question "why does it happen". If you want to know how to workaround this, there are many ways you can copy an object. Please give a look at this link
Upvotes: 0
Reputation: 71908
They are the same object. Here is a quick and dirty way to create a clone of sorts:
Animals.push(Object.create(Cattypes[0]));
Won't work on olders browsers that don't support Object.create
.
Now, if you do Animals[0].price -= 140;
, Cattypes[0]
won't be affected. But, because this method is relies on prototypes, if you change Cattypes[0].price
without setting Animals[0].price
first, Animals[0].price
will also change.
Upvotes: 2
Reputation: 5317
Objects are passed by reference, not by value - Cattypes[0]
and Animals[0]
are the same object, not identical objects.
Upvotes: 1