javascript之對象學習筆記(二)–類比類實現

來源:互聯網
上載者:User

     1.執行個體屬性、執行個體方法與類屬性、類方法

function circle(r){

this.redius = r;   //redius屬性執行個體屬性,即該類型的每個執行個體對象都具有copy該屬性

}

circle.PI = 3.14;   //P為circle類的一個類屬性,跟執行個體無關

circle.prototype.area = function (){ return  circle.PI*this.redius*this.redius }; //area是一個執行個體方法,裡面引用類屬性PI

circle.init = function (){ return new circle(1);}init()為類方法,此方法用於建立一個半徑為1的圓形

執行個體屬性、執行個體方法類試java中的非靜態屬性或函數

類屬性、類方法類似java中的靜態屬性或函數 

   

      2.類繼承

             動物類:

function animal(){

this.type = "animal";

}

貓類:

function cat (name,age){

this.name = name;

this.age = age;

}

如何讓cat繼承animal類呢?

1.建構函式繫結模式:

function cat(name,age){

animal.call(this,[arguments])  //arguments為傳遞的參數數組,this參數為調用此函數的對象,這裡是cat

this.name = name;

this.age = age;

}

var  c = new car('tom',19);

console.log(c.type);  

2.原型繼承模式

  cat.prototype = new animal();//給cat的原身prototype重新初始化

  cat.prototype.constuctor = cat;//上面已經將原身prototype重新賦值,原身prototype的constructor就不存在,所以這裡需要重新指定constructor值,這裡是cat,
                                                               否則後面的繼承鏈出問題

  var  c = new car('tom',19);

  console.log(c.type);  

  總之編程時候要遵守一點如果重新賦值o.prototype的值:

  o.prototype={};

   接下來務必要給o.prototype.constructor賦值:

   o.prototype.constructor = o;

相關文章

聯繫我們

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