javascript中继续组合继承的问题

etghthte etghthte 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区

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变为原型中定义这样呢?而且只针对引用类型的变量?
...全文
评论 12
收藏 已收藏
分享
返回顶部
etghthte
JavaScript 87,984 成员 224,680 内容