关于原型对象的问题function Person(name,age,job){ this.name=name; this.age=age; this.job=job;
}
Person.prototype.friends=['shell','dom','bom'];
Person.prototype.color='red';var person2=new Person('Mark',29,'teach');
person2.color='green';console.log(person2.color);//greenvar person1=new Person('jack',19,'stu');console.log(person1.color);//redperson1.friends.push('window');console.log(person1.friends);//["shell", "dom", "bom", "window"]console.log(person2.friends);//["shell", "dom", "bom", "window"]问题描述:1.我们可以通过对象实例访问原型中的值,却不能通过对象实例来重写原型中的值。如果在实例中添加了一个与对象原型中重名的属性,该属性将会屏蔽原型中那个属性。(javascript高级程序设计(第三版))如以上代码前两个显示的测试结果 :console.log(person2.color);//greenconsole.log(person1.color);//red2.关键问题是,改变了person1的friends,为什么引起了person1原型中值friends的改变??如上代码后两个测试结果:console.log(person1.friends);//["shell", "dom", "bom", "window"]
console.log(person2.friends);//["shell", "dom", "bom", "window"]
1 回答

慕的地10843
TA贡献1785条经验 获得超8个赞
person1.friends.push('window');
这里的 firends 属性仍旧取的是原型 Person.prototype.friends,因为 person1 并没有自己的属性 friends,push 并不能产生一个新的数组。
添加回答
举报
0/150
提交
取消