1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>原型链的问题</title> 6 </head> 7 <body> 8 9 <script> 10 //定义在构造函数内的属性并不会在实例间共享 11 //因为new的执行中只是把这些属性赋给新创建的对象,然后把新对象返回 12 //也就是说这些属性是属于实例的 13 function SS(){ 14 this.color = ['red','green']; 15 } 16 17 let s1 = new SS(); 18 let s2 = new SS(); 19 20 console.log(s1); 21 console.log(s2); 22 23 s1.color.push('blue'); 24 console.log(s1); //red, green, blue 25 console.log(s2); //red, green 26 27 28 console.log('-------原型模式下------------'); 29 30 //原型模式下实例共享原型属性产生的问题 31 function Person(){} 32 Person.prototype = { 33 constructor:Person, 34 color:['red','green'] 35 }; 36 let person1 = new Person(); 37 let person2 = new Person(); 38 39 console.log(person1.color); 40 console.log(person2.color); 41 42 person1.color.push('blue'); 43 44 console.log(person1.color); //red, green, blue 45 console.log(person2.color); //red, green, blue 46 47 48 49 //原型链下依然会有共享引用属性的问题 50 function SuperType(){ 51 this.color = ['red','green']; 52 } 53 function SubType(){} 54 55 SubType.prototype = new SuperType(); 56 let inst1 = new SubType(); 57 let inst2 =new SubType(); 58 console.log(inst1); 59 console.log(inst2); 60 61 inst1.color.push('blue'); 62 console.log(inst1); //red, green, blue 63 console.log(inst2); //red, green, blue 64 65 </script> 66 </body> 67 </html>
标签:console,log,color,问题,原型,new,green,red From: https://www.cnblogs.com/polin/p/17134536.html