继承问题 :求指教
function SuperType(){
this.name='s;'
this.colors = ["red", "blue", "green"];
}
function SubType(){
}
//inherit from SuperType
SubType.prototype = new SuperType();
var instance1 = new SubType();
var instance2 = new SubType();
instance1.name='ssss';
instance1.colors=["red", "blue"];
alert(instance1.colors); //"red,blue,green,black"
alert(instance1.name); //"ssss"
alert(instance2.colors); //"red,blue,green,black"
alert(instance2.name); //"s"
instance2.name 为什么没有改变
function SuperType(){
this.name='sdsd';
this.colors = ["red", "blue", "green"];
}
function SubType(){
//inherit from SuperType
SuperType.call(this);
}
var instance1 = new SubType();
instance1.colors.name='aaaaaaa';
instance1.colors.push("black");
alert(instance1.colors); //"red,blue,green,black"
alert(instance1.name); //"a"
var instance2 = new SubType();
instance2.colors.name='bbbbbbb';
alert(instance2.colors); //"red,blue,green"
alert(instance2.name); //"a"
instance2.name和instance1.name 都没有改变
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
console.log(a.key)
)和写(a.key = 1
)的时候是不一样的,读的时候会一直查下去,写的时候发现本身没有就直接创建赋值了。{name, colors}
。那你改对colors添加name是不会影响到name属性的。哥们 你先仔细读一遍你给出的代码,看看有没有什么问题。
我大致懂了你的意思,首先你要明白引用类型和基本类型的区别,instance1和instance2的name属性都是字符串属于基本类型,instance1.name和instance2.name在内存空间里是独立的,互不影响的。而color属性时一个数组属于引用类型,instance1.color和instance2.color中存储只是color数组的地址,也就是说两者指向的是同一个数组,因此只要color数组发生了改变,instance1.color和instance2.color得到的值都会发生改变。
举个例子吧:
最后,给你推荐几本书《javascript高级教程》《javascript语言精粹》《javascript忍者秘籍》,从你的问题可以看出你js基础有所欠缺,多看看书对你有帮助的