1 <!DOCTYPE html>
2 <html lang="en">
3 <head>
4 <meta charset="UTF-8">
5 <title>寄生组合继承</title>
6 </head>
7 <body>
8 <script>
9 function inHeritPrototype(Son,Parent) {
10 var prototype=Object.create(Parent.prototype);
11 /*
12 es5语法,最后会返回一个new F()的实例,此实例的__proto__指向Parent.prototype
13 相当于function create(obj){
14 function F(){}
15 F.prototype=obj;
16 return new F()
17 }
18 */
19 prototype.constructor=Son;
20 Son.prototype=prototype;
21 }
22 function Parent(name){
23 this.name=name;
24 this.colors=["red","black","blue"];
25 }
26 Parent.prototype.sayName=function () {
27 alert(this.name);
28 }
29 function Son(name,age) {
30 Parent.call(this,name);
31 this.age=age;
32 }
33 inHeritPrototype(Son,Parent);
34 Son.prototype.sayAge=function(){
35 alert(this.age);
36 }
37 var son=new Son('zxf',25);
38 console.log(Parent.prototype)
39 console.log(Son.prototype);//此处子类的原型没有继承父类的属性,而是直接继承了父类原型上的属性和方法,
40 //继承父类属性的语句是Parent.call()这句话实现的,这样就避免了组合式继承的缺点-调用了两个父类的构造函数,导致给子类的原型上添加了父类的实例属性
41 //最完美的是子类的原型上只继承父类的原型的属性,而不是继承父类实例的属性,通过寄生组合式继承可以实现子类实例之间修改引用类型的属性时互不影响
42 //因为这句话Parent.call()让每个子类都有个父类属性的一个副本,是一个等于在子类实例上各自创建了属性而不是指向父类的属性,另外
43 //通过inHeritPrototype方法实现了子类只继承父类原型上的方法和属性,这里实现了属性和方法的共享,可谓完美啊
44 </script>
45 </body>
46 </html>