javascript中继续组合继承的问题
function SuperType(name) {
this.name = name;
this.colors = ["red", "blue", "green"];
}
SuperType.prototype.sayName = function() {
alert(this.name);
};
function SubType(name, age) {
SuperType.call(this, name);
this.age = age;
}
SubType.prototype = new SuperType();
SubType.prototype.sayAge = function() {
alert(this.age);
};
var instance1 = new SubType("Nic", 28);
instance1.colors.push("black");
//instance1.colors = ["red", "blue", "green", "black"];
alert(instance1.colors);
var instance2 = new SubType("Gre", 40);
alert(instance2.colors);
为什么上面这段代码运行显示两个colors不一样;但下面那段代码运行显示却一样?
function SuperType() {
this.name = "Nic";
this.colors = ["red", "blue", "green"];
}
SuperType.prototype.sayName = function() {
alert(this.name);
};
function SubType() {
//SuperType.call(this, name);
this.age = 25;
}
SubType.prototype = new SuperType();
SubType.prototype.sayAge = function() {
alert(this.age);
};
var instance1 = new SubType();
instance1.colors.push("black");
//instance1.colors = ["red", "blue", "green", "black"];
alert(instance1.colors);
var instance2 = new SubType();
alert(instance2.colors);
是不是function SuperType(name)与function SubType(name, age)对于SubType.prototype = new SuperType();有影响呢?即是不是因为SuperType与SubType有参数导致colors不受原型的影响,而没有参数就受原型的影响致使colors变为原型中定义这样呢?而且只针对引用类型的变量?
...全文


