问题是: 我预计动物[0]的价格会下降,但它也会降低Cattypes [0]的价格。这是怎么发生的?
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);
答案 0 :(得分:2)
它们是同一个对象。这是一种快速而又脏的方法来创建各种类型的克隆:
Animals.push(Object.create(Cattypes[0]));
不适用于不支持Object.create
的旧版浏览器。
现在,如果您执行Animals[0].price -= 140;
,Cattypes[0]
将不会受到影响。但是,由于此方法依赖于原型,如果您先更改Cattypes[0].price
而不先设置Animals[0].price
,Animals[0].price
也会更改。
答案 1 :(得分:1)
对象通过引用传递,而不是按值传递 - Cattypes[0]
和Animals[0]
相同的对象,不相同的对象。
答案 2 :(得分:0)
在JavaScript中将对象传递给函数时,将传递对此对象的引用。不复制对象。将Cattypes[0]
添加到Animals
数组时,不会复制该对象。您正在访问同一个对象。
Animals[0].price -= 140; // here, Animals[0] is the same as Cattypes[0]
这是“为什么会发生”这个问题的回答。 如果您想知道如何解决此问题,可以通过多种方式复制对象。请查看this link