function SuperType() {
this.name = "Nic";
this.colors = ["red", "blue", "green"];
}
SuperType.prototype.sayName = function() {
alert(this.name);
};
function SubType() {
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);
instance1.name = "Greg";
instance1.sayName();
instance1.age = 50;
instance1.sayAge();var instance2 = new SubType();
alert(instance2.colors);
instance2.sayName();
instance2.sayAge();
上面代码中instance1.colors.push("black");时输出instance1与instance2的colors时都为red,blue,green,black;但改为下面注释那句时就互不影响了。为什么会这样?是不是push()有什么奥秘?javascriptfunctioncolors
第二次弹出red, blue, green你说的情况是在什么浏览器下执行的?
是在firefox下执行的。您的意思是firefox下的情况就是我这个情况?那么IE呢?(我的IE暂时用不到,提示DNS错误)
即无论怎么改两次都显示有black?
如果真的是这样的话那就是什么意思呢?按道理说换成注释那句是只影响instance1的喔,不影响instance2的,除非javascript在继承中本来就有个奇怪的定义:引用类型的变量不同于其他实例变量,即引用类型的变量特殊对待了。。无论定义在哪里都为原型中定义
===================================
否,都是一次有一次无。
原型中的属性是唯一 共享的(在读的时候)
所以你还是在 new的时候初始化变量把function SubType() {
this.age = 25;
SuperType.apply(this);
}
SubType.prototype = SuperType.prototype;
SubType.prototype.sayAge = function() {
alert(this.age);
};
function SubType() {
this.age = 25;
SuperType.call(this);
}
}
test.prototype = {
test : function(){}
}
var ins1 = new test;
var ins2 = new test;
alert( ins1.test === ins2.test )结果为true,在同一内存区域中,也就是说他们调用的是同一个方法,同理,push改变了数组,也就反应在了别的实例上面,不同实例原型链中对于父类的引用是同一对象,再看看下面的代码:function test2(){
this.test = function(){}
}
var ins1 = new test2;
var ins2 = new test2;
alert( ins1.test === ins2.test );当然,这里的结果就是flase,这里,JS为每个test2类的实例对象都开辟了一块内存空间来存放test方法,所以当你alert的时候,由于是两个不同的方法(虽然他们的功能或者代码完全一致),这里还是显示false,这就是JS的两种面向对象的实现方式,第一种的原型链式的,第二种是构造函数式的。
没有在对象上对colors成员重新赋值,所以访问仍然是原型链上的成员,也就是说两个对象上的colors成员是同一个对象,所以会互相影响
你写一句
alert(SubType.prototype.colors);
就明白了对象成员colors的访问过程是:
1.查找对象本身有无colors成员,如果有,返回该成员
2.如果1没有找到,则查找原型链上有无colors成员,有则返回该成员,否则undefined仔细理解,你的疑惑就都解决了