JavaScript繼承方式(3)

來源:互聯網
上載者:User

3,繼承工具函數三

view sourceprint?1 /** 

2  * @param {Function} subCls 

3  * @param {Function} superCls 

4  */

5 function extend(subCls,superCls) { 

6     subCls.prototype = new superCls();   

7 }

父類,按原型方式寫,即屬性和方法都掛在原型上。

view sourceprint?1 /** 

2  *  父類Person 

3  */

4 function Person(){} 

5 Person.prototype.nationality = China; 

6 Person.prototype.getNationality = function() {return this.nationality;} 

7 Person.prototype.setNationality = function(n) { this.nationality = n;}

子類繼承與父類

view sourceprint?1 function Man() {} 

2 extend(Man,Person);

繼承父類的屬性和方法後,再添加子類自有屬性,方法 

view sourceprint?1 Man.prototype.name = jack; 

2 Man.prototype.getName = function() { return this.name;} 

3 Man.prototype.setName = function(n) { this.name=n;}

測試如下,

view sourceprint?1 var m = new Man(); 

2 console.log(m); 

3 console.log(m instanceof Person);

可以看到這種寫類方式,繼承方式完全採用原型機制。

 

4,繼承工具函數四

這種方式是目前比較流行的,51ditu網站的開發就是按照這種模式的。

view sourceprint?01 /** 

02  * @param {Function} subCls 子類 

03  * @param {Function} superCls 父類 

04  */

05 function extend(subCls,superCls) {   

06     //暫存子類原型 

07     var sbp = subCls.prototype; 

08     //重寫子類原型--原型繼承 

09     subCls.prototype = new superCls(); 

10     //重寫後一定要將constructor指回subCls 

11     subCls.prototype.constructor = subCls; 

12     //還原子類原型 

13     for(var atr in sbp) { 

14         subCls.prototype[atr] = sbp[atr]; 

15     } 

16     //暫存父類   

17     subCls.supr = superCls; 

18 }

按 建構函式+原型 方式寫類,即屬性掛在this上,方法掛在prototype上。

view sourceprint?01 /** 

02  *  父類Person 

03  */

04 function Person(nationality){ 

05     this.nationality = nationality; 

06 } 

07 Person.prototype.getNationality = function() {return this.nationality;} 

08 Person.prototype.setNationality = function(n) { this.nationality = n;} 

09   

10 /** 

11  *  子類Man 

12  */

13 function Man(nationality,name) { 

14     Man.supr.call(this,nationality); //很重要的一句,調用父類構造器 

15     this.name = name; 

16 } 

17 Man.prototype.getName = function() {return this.name;} 

18 Man.prototype.setName = function(n) {this.name=n;}

注意子類Man中要顯示的調用父類構造器已完成父類的屬性/欄位拷貝。

extend調用,建立Man的執行個體

view sourceprint?1 extend(Man,Person); 

2 var m = new Man(USA,jack); 

3 console.log(m); 

4 m.setName(lily); 

5 console.log(m.name);

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.