JavaScript之ES6中的class與繼承

來源:互聯網
上載者:User

標籤:super   tor   tag   new   類繼承   標識   對象   一個   extend   

參考:https://www.imooc.com/article/17389

https://www.cnblogs.com/chenyangsuaige/p/6130737.html

繼承可以實現很好的封裝,子類直接對父類的方法進行重用,還可以添加自己的屬性和方法。

原型對象prototype是類的唯一識別碼,類的繼承是基於prototype的。

es5中類的繼承

//es5 類的繼承四部曲//1、建立父類function Parent(name){    this.name = name;}Parent.prototype.location = "earth";Parent.prototype.getName = function(){    console.log(this.name);}//2、建立子類function Son(name,age){    Parent.call(this,name);//子類調用父類的建構函式    this.age = age;}//3、建立繼承,子類的原型對象是父類的一個執行個體Son.prototype = new Parent();//這裡Son.prototype._proto_=Parent.prototype,Son.prototype.constructor=Parent//修正子類的constructorSon.prototype.constructor = Son;//4、添加子類成員Son.prototype.id = 123;Son.prototype.getAge = function(){  console.log(this.age);}//建立一個執行個體var student1 = new Son(‘asd‘,‘11‘);student1.getName();//asd,繼承自父類的方法student1.getAge();//11,子類自己的方法

es6中類的繼承

//es6中class與繼承//建立父類class Parent{    constructor(name){        this.name = name;    }//!!!注意,這裡沒有逗號    getName(){        console.log(this.name);    }}
//子類繼承自父類class Son extends Parent{ constructor(name,age){ super(name);//super指向父類的執行個體對象,調用父類的constructor,必須先調用super方法,子類才能使用this this.age = age;//子類繼承父類的this對象並修改 } getName(){ super.getName();//調用父類的方法 console.log(‘son‘); }}

注意:

1、es6類中只能定義constructor屬性和方法,方法全部定義在類的prototype中,且方法不可枚舉;

2、es6中類的constructor屬性相當於es5中的建構函式,如果沒有定義constructor屬性,預設會添加一個空的constructor;

3、es5中,繼承是子類先建立自己的執行個體對象this,然後通過Parent.call(this)或Parent.apply(this)調用父類的方法;es6中,繼承是父類先建立自己的執行個體對象this,然後子類繼承父類的this,在子類的constructor中修改this。

JavaScript之ES6中的class與繼承

聯繫我們

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