[js高手之路]寄生组合式继承的优势

在之前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

组合继承有个缺点,父类的构造函数会被调用两次.

第11行,设置子类原型对象(prototype),调用了第一次

第9行,实例化对象的时候,又调用一次

构造函数的目的是为了复制属性,第9行肯定是不能少的,第11行的目的是为了获取到父类原型对象(prototype)上的方法,基于这个目的,有没有别的方法

可以做到 在不需要实例化父类构造函数的情况下,也能得到父类原型对象上的方法呢? 当然可以,我们可以采用寄生式继承来得到父类原型对象上的方法

 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

 

其实,说白了寄生组合式继承就是一个借用构造函数 + 相当于浅拷贝父类的原型对象

 

posted @ 2017-08-27 16:28  ghostwu  阅读(4032)  评论(0编辑  收藏  举报
Copyright ©2017 ghostwu