js對象之間的繼承

來源:互聯網
上載者:User

標籤:

js的對象之間的繼承拋棄了原型與構造器的概念,而轉為字面量對象之間進行屬性拷貝的方式進行繼承。 

首先我們來寫一個封裝好的繼承函數:

 

function extend(parent){    var child={};    for(var i in parent){        child[i]=parent[i];    }    child.uber=parent;    return child;}

 

 函數有一個實參parent,函數內部建立一個空的子物件,這個子物件就像一個白的畫板,逐漸的將父物件上的內容臨摹上去。for迴圈當中是將父物件中的屬性和方法逐個複製給子物件。再將子物件的uber指向父物件,這樣調用子物件的uber屬性就可以調用父物件的屬性和方法了,這相當與java中的super,為什麼js當中不用super呢,因為super在js中是保留字,所以採用德語與“super”同義的“uber”來替代。

 

下面來看看這個函數的實際應用,首先建立一個父物件:

 

var Shape={    color:"blue",    name:"shape",    getName:function(){        return this.name;    }}

 

接著我們來實現繼承,並擴充和重寫子物件的一些方法:

 

var circle=extend(Shape);circle.name="circle";circle.getName=function(){    return "parentName:"+this.uber.getName()+" childName:"+this.name;}circle.getS=function(){    return this.radius*this.radius*3.14;}circle.init=function(radius){    this.radius=radius;}


首先使用extend函數實現繼承

子物件添加了新的name屬性和新的getName方法,還有擴充的getS方法和init初始化方法

getName中this.uber.getName()調用父物件的getName()方法,得到父物件的name屬性,this.name得到自身的name屬性。

接下來執行方法:

 

circle.init(5);console.log(circle.name+","+circle.uber.name);console.log(circle.getName()+","+circle.uber.getName());console.log(circle.getS());/*結果:circle,shapeparentName:shape childName:circle,shape78.5*/

 

js對象之間的繼承

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.