JavaScript建構函式學習筆記

來源:互聯網
上載者:User

標籤:

1 理解Javascript constructor實現原理

在 JavaScript 中,每個函數都有名為“prototype”的屬性,用於引用原型對象。此原型對象又有名為“constructor”的屬性,它反過來引用函數本身。這是一種循環參考

 

2 JavaScript探秘:建構函式 Constructor

除了建立對象,建構函式(constructor) 還做了另一件有用的事情—自動為建立的新對象設定了原型對象(prototype object) 。原型對象存放於 ConstructorFunction.prototype 屬性中。

3 JavaScript繼承方式詳解

1)原型鏈繼承

function Parent(){        this.name = ‘mike‘;    }    function Child(){        this.age = 12;    }    Child.prototype = new Parent();//Child繼承Parent,通過原型,形成鏈條    var test = new Child();    alert(test.age);    alert(test.name);//得到被繼承的屬性}

2)組合繼承

   function Parent(age){        this.name = [‘mike‘,‘jack‘,‘smith‘];        this.age = age;    }    Parent.prototype.run = function () {        return this.name  + ‘ are both‘ + this.age;    };    function Child(age){        Parent.call(this,age);//對象冒充,給超類型傳參    }    Child.prototype = new Parent();//原型鏈繼承    var test = new Child(21);//寫new Parent(21)也行    alert(test.run());//mike,jack,smith are both21

   使用原型鏈實現對原型屬性和方法的繼承,而通過借用建構函式來實現對執行個體屬性的繼承。這樣,既通過在原型上定義方法實現了函數複用,又保證每個執行個體都有它自己的屬性。

4 JavaScript 繼承詳解

一個系列文章,沒有看完

JavaScript建構函式學習筆記

聯繫我們

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