javascript 繼承 -自己動手實踐

來源:互聯網
上載者:User

javascript 繼承 , 老生長談的東西, 大家應該都很熟悉了, 平時工作基本不會直接使用, 這段時間不忙, 所以補習了下相關基礎知識 ,自己動手實踐, 加深理解:

基類定義如下:

    // base class    function Animal(t)    {      if(typeof t==='string')        this.type=t;      else      {        if(t)            this.type=t.toString();        else            this.type='Animal'      }            this.speak=function(str)      {        if(str)            console.log(this.type+' said '+str);        else            throw "please specify what you want to say!";      }    }

1.原型繼承 (javascript 類庫本身基於原型繼承)

 String, Number , Boolean 這三大原始類型 我們可以很直接的通過prototype 檢查到他們繼承自Object.

 Date, RegExp ,Array 這三應該是間接繼承了Object, 他們的prototype屬性很特殊 :

 Date.prototype =Invalid Date

 RegExp.prototype=/(?:)/

 Array.prototype=[]

 原型繼承代碼如下: (可以看到Mokey 原型鏈上的Animal和Object)

    // Monkey : Animal     function Monkey(name,age)    {      this.name=name;      this.age=age;    }        Monkey.prototype=new Animal('Monkey');        // Example 01    var m=new Monkey('codeMonkey',10);        /*        Monkey:        age: 10        name: "codeMonkey"            __proto__: Animal            speak: function (str)            type: "Monkey"                __proto__: Animal                constructor: function Animal(t)                    __proto__: Object         */    console.log(m.type); // Monkey    console.log(m.name); // codeMonkey    console.log(m.age); // 10    m.speak('hello world') // Monkey said hello world 

 

2. 調用父類建構函式 ( 通過傳遞子類的this指標 , 將原本是父類的公開成員直接添加到了子類中,從子類原型鏈中無法看出繼承關係)

    // Human:Animal     function Human(id,name)    {       // call base class's constuctor function      Animal.call(this,'Human');             this.id=id;      this.name=name;    }        var h=new Human(1,'leon');        /*    id: 1    name: "leon"    speak: function (str)    type: "Human"        __proto__: Human        constructor: function Human(id,name)            __proto__: Object    */    h.speak('hello world'); // Human said hello world     console.log(h.type); // Human

 

相關文章

聯繫我們

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