在以前javascript面向对象系列的文章里面,咱们已经探讨了组合继承和寄生继承,回顾下组合继承:javascript
1 function Person( uName ){ 2 this.skills = [ 'php', 'javascript' ]; 3 this.userName = uName; 4 } 5 Person.prototype.showUserName = function(){ 6 return this.userName; 7 } 8 function Teacher ( uName ){ 9 Person.call( this, uName ); 10 } 11 Teacher.prototype = new Person(); 12 13 var oT1 = new Teacher( 'ghostwu' ); 14 oT1.skills.push( 'linux' ); 15 var oT2 = new Teacher( 'ghostwu' ); 16 console.log( oT2.skills ); //php,javascript 17 console.log( oT2.showUserName() ); //ghostwu
组合继承有个缺点,父类的构造函数会被调用两次.php
第11行,设置子类原型对象(prototype),调用了第一次html
第9行,实例化对象的时候,又调用一次java
构造函数的目的是为了复制属性,第9行确定是不能少的,第11行的目的是为了获取到父类原型对象(prototype)上的方法,基于这个目的,有没有别的方法linux
能够作到 在不须要实例化父类构造函数的状况下,也能获得父类原型对象上的方法呢? 固然能够,咱们能够采用寄生式继承来获得父类原型对象上的方法函数
1 function Person( uName ){ 2 this.skills = [ 'php', 'javascript' ]; 3 this.userName = uName; 4 } 5 Person.prototype.showUserName = function(){ 6 return this.userName; 7 } 8 function Teacher ( uName ){ 9 Person.call( this, uName ); 10 } 11 12 function object( o ){ 13 var G = function(){}; 14 G.prototype = o; 15 return new G(); 16 } 17 18 function inheritPrototype( subObj, superObj ){ 19 var proObj = object( superObj.prototype ); //复制父类superObj的原型对象 20 proObj.constructor = subObj; //constructor指向子类构造函数 21 subObj.prototype = proObj; //再把这个对象给子类的原型对象 22 } 23 24 inheritPrototype( Teacher, Person ); 25 26 var oT1 = new Teacher( 'ghostwu' ); 27 oT1.skills.push( 'linux' ); 28 var oT2 = new Teacher( 'ghostwu' ); 29 console.log( oT2.skills ); //php,javascript 30 console.log( oT2.showUserName() ); //ghostwu
其实,说白了寄生组合式继承就是一个借用构造函数 + 至关于浅拷贝父类的原型对象this