【发布时间】:2015-12-27 23:42:01
【问题描述】:
我在这段代码 sn-p 中使用原型继承:
function SuperType() {
this.colors = ["red", "blue", "green"];
this.x = 1;
}
function SubType() {}
SubType.prototype = new SuperType();
var instance1 = new SubType();
instance1.colors.push("black");
instance1.x = 2;
//alert(instance1.colors); // "red,blue,green,black"
//alert(instance1.x); // 2
var instance2 = new SubType();
alert(instance2.colors); // "red,blue,green,black"
alert(instance2.x); // 1
我希望输出是
"red,blue,green"
1
或
"red,blue,green,black"
2
但我明白了:
"red,blue,green,black"
1
为什么?
【问题讨论】:
-
您刚刚创建了
SubType的新实例。试试var instance2 = instance1 -
数组和对象通过引用传递,而对于原始类型(字符串、数字等),引用是值,related
标签: javascript inheritance prototype prototypal-inheritance prototype-programming