ES6新特性(五)class類


一、創建類和對象

  1.1. 在ES5中使用的是function關鍵字創建類, ES6引入了 class 關鍵字來創建類。

  1.2. 創建類的實例使用 new 關鍵字

  1.3. 類的 constructor 構造函數:用於傳遞參數,返回實例對象,通過 new 關鍵字生成實例時,自動調用該方法。如果沒有顯式聲明構造函數,在類的內部會自動創建一個默認的constructor()構造函數。

  1.4. 在類中聲明實例方法則使用  方法名(){ 方法體 } ,並且在各方法之間是不需要使用逗號隔開的。

 1 //創建類和對象
 2 class Test{  3             
 4     constructor(str){//構造函數
 5         this.str = str;  6  }  7             
 8     say(){        //實例方法
 9         console.log(this.str);//hello
10  } 11 } 12         
13 let test = new Test('hello');//生成實例
14 test.say();//調用實例方法

    在上述代碼中,創建了一個Test類,類的內部聲明了一個構造函數和一個實例函數,外部使用new關鍵字創建了類的實例對象,在創建類的實例對象時會自動調用構造函數,並把 ‘hello’ 字符串賦值給Test類的 str 屬性,然后使用 test 對象調用實例函數say()。

    注意:在類的內部聲明的方法不需要加function關鍵字,構造方法只能聲明一個或者不聲明使用默認的構造方法,否則報錯。

 

二、繼承

  2.1. 類使用 extends 關鍵字來繼承父類。

  2.2. 在子類中使用 super 關鍵字來調用父類的屬性和方法。如果在子類的構造函數中使用this關鍵字,那么super關鍵字的代碼必須在子類構造函數的第一行,否則報錯。

 1 //類的繼承
 2 //父類Parent
 3 class Parent{  4             
 5    constructor(str){//父類的構造函數
      this.str = str;
   {
6 7 } 8 9 //子類 Child 使用extends繼承Parent類 10 class Child extends Parent{ 11 12 constructor(str){ 13 super(); //super關鍵字調用父類的構造方法 14 this.str = str; //使用this關鍵字給Child的屬性str賦值15 } 16 17 say(){ 18 console.log('子類的實例方法'); 19 } 20 } 21 22 let child = new Child('hello');//生成Child類的實例對象 23 child.say();//調用child類的實例方法

 

  

三、靜態方法和靜態屬性

  3.1. 靜態方法和靜態屬性都是使用 static 修飾,直接使用類名調用。

 1 //靜態方法和靜態屬性
 2 class Test{  3             
 4     static say(str){//靜態方法
 5         console.log(str);//hello
 6  }  7     static str2 = 'world';//靜態屬性
 8 }  9 console.log(Test.str);//使用類名調用靜態屬性 : world
10 Test.say('hello');//使用類名調用靜態方法

 

 

 

  

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM