javascript原型繼承

來源:互聯網
上載者:User

標籤:===   lan   官方網站   var   parent   技術   cti   his   struct   

用一張圖來表示新的原型鏈:

 

封裝一個inherits()函數,函數F用於橋接

function inherits(Child, Parent) {    var F = function () {};    F.prototype = Parent.prototype;    Child.prototype = new F();    Child.prototype.constructor = Child;}

這樣inherits()函數就可以重複使用了
function Student(props) {    this.name = props.name || ‘Unnamed‘;}Student.prototype.hello = function () {    alert(‘Hello, ‘ + this.name + ‘!‘);}function PrimaryStudent(props) {    Student.call(this, props);    this.grade = props.grade || 1;}// 實現原型繼承鏈:inherits(PrimaryStudent, Student);// 綁定其他方法到PrimaryStudent原型:PrimaryStudent.prototype.getGrade = function () {    return this.grade;};// 建立xiaoming:var xiaoming = new PrimaryStudent({    name: ‘小明‘,    grade: 2});xiaoming.name; // ‘小明‘xiaoming.grade; // 2// 驗證原型:xiaoming.__proto__ === PrimaryStudent.prototype; // truexiaoming.__proto__.__proto__ === Student.prototype; // true// 驗證繼承關係:xiaoming instanceof PrimaryStudent; // truexiaoming instanceof Student; // true

 

原型繼承 - 廖雪峰的官方網站 (選自 @廖雪峰)

https://www.liaoxuefeng.com/wiki/001434446689867b27157e896e74d51a89c25cc8b43bdb3000/0014344997013405abfb7f0e1904a04ba6898a384b1e925000

 

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.