1. 程式人生 > 實用技巧 >es6類

es6類

ES6類

定義:

1 2 3 4 5 6 7 8 9 10 class Animal { //建構函式,建立這個類時會執行的函式 constructor(color){ //this當前物件 console.log("構造") this.color=color } } const myCat = new Animal("白"); console.log(myCat)

  

  • constructor: 建構函式
  • this : 當前例項
  • super: 它的父類

類的繼承 class Cat extends Animal

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 class Animal { constructor(color){ this.color= color; } eat() { console.log("吃飯"); } } //繼承 class Cat extends Animal { // 建構函式 constructor(color,name){ //父類 super(color); // 當前例項 this.name = name; } eat(){ super.eat(); console.log("吃啊了") } } let myCat = new Cat("黑白","皮皮") myCat.eat(); console.log(myCat.name);
console.log(myCat.color)

  

通過static關鍵字可以宣告靜態的方法,靜態方法歸屬於類而不是例項 也可宣告靜態變數 普通的方法歸屬於例項,需要通過例項呼叫
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 class Animal {<br>    //靜態變數 static name = "動物的類" constructor(color,name){ this.color = color; this.name = name;
} //通過static關鍵字可以宣告靜態的方法,靜態方法歸屬於類而不是例項 static getname() { console.log("靜態方法"); return this; } //普通方法歸屬於例項 eat(){ console.log(this.name +"吃飯"); } } let myCat =new Animal("白色","學學"); let yourCat = new Animal("白色", "球球"); //通過例項呼叫方法 myCat.eat(); yourCat.eat(); //例項沒有靜態方法 // console.log(myCat.getname()); console.log(Animal.getname()); console.log(Animal.name); // console.log(Animal.prototype.name);