關于原型對象的問題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"]
關于原型對象的問題
飲歌長嘯
2018-09-06 14:14:26