js组合式继承
组合式继承是比较经典的继承,但是也有比较严重的缺点就是连两次调用了父类的构造函数。
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>Title</title> 6 </head> 7 <body> 8 <script> 9 function SuperType(name){ 10 this.name=name; 11 this.colors=["red","blue","green"]; 12 } 13 SuperType.prototype.sayName=function(){ 14 console.log(this.name); 15 } 16 function SubType(name,age){ 17 SuperType.call(this,name);//此时会执行SuperType函数,其中的this就会指向SubType,第二次调用父类 18 this.age=age; 19 } 20 SubType.prototype=new SuperType();//第一次调用父类 21 SubType.prototype.constructor=SubType; 22 SubType.prototype.sayAge=function(){ 23 console.log(this.age); 24 } 25 var instance1=new SubType("zxf",24); 26 console.log(SubType.prototype); 27 instance1.colors.push("black"); 28 console.log(instance1.colors);//["red","blue","green","black"] 29 instance1.sayName();//"zxf" 30 instance1.sayAge();//24 31 delete instance1.colors; 32 var instance2=new SubType("jay",36); 33 console.log(instance2.colors);//["red","blue","green"] 34 instance2.sayName();//"jay" 35 instance2.sayAge();//36 36 /* 37 * 此方法有弊端,就是 SubType.prototype=new SuperType();这句话会导致子类的原型指向父类,并且会有父类的属性name,colors, 38 * 继承这些属性其实在子类中用SuperType.call()已经实现了,这句话会让子类的实例拥有colors,name属性,并且会覆盖子类原型上的name,colors属性,就是上面一行提到的 39 * 所以这是个弊端,可以用寄生组合式继承来避免 40 * */ 41 </script> 42 </body> 43 </html>