一、constructor(構造器)(今後用的多)
-
constructor構造器的作用就是,每當 new 這個類的時候,必會優先執行constructor構造器中的代碼;
傳統構造函數:
function Animal (name, age) { //實例屬性 this.name = name; this.age = age; } const a1 = new Animal('dog', 3);
class類:
class Animal { constructor(name, age){ //實例屬性 this.name = name; this.age = age; } } const a2 = new Animal('cat', 2);
-
每一個class類中,都有一個constructor構造器,如果沒有手動指定constructor構造器,那麼可以認爲class類內部,有個隱形的,空的constructor構造器。
class Animal { //constructor(){ 這裏就是隱形的,空的constructor構造器 //} }
二、使用 static 創建靜態屬性(今後用的不多)
-
什麼是靜態屬性:
通過 “構造函數” 直接訪問到的屬性; 例如下面的 sounds,直接掛載給了 Animal ,所以 sounds 是 靜態屬性 ```javascript function Animal (name, age) { this.name = name; this.age = age; } Animal.sounds = 'yayaya'; console.log(Animal.sounds)// yayaya const a1 = new Animal('dog', 3); console.log(a1.sounds)// undefined console.log(a1.name)//dog console.log(a1.age)//3 ``` 相反的是,name,age,能被new出來的實例a1所訪問到,所以 name 和 age 是 **實例屬性**
-
在 class 內部怎麼定義 靜態屬性
通過 static 關鍵字修飾的屬性,就是 靜態屬性class Animal { constructor(name, age){ this.name = name; this.age = age; } static sounds = 'yayaya'; } console.log(Animal.sounds)//yayaya const a2 = new Animal('cat', 2); console.log(a2.sounds)//undefined console.log(a2.name)//cat console.log(a2.age)//2
三、實例方法(今後會經常用到)
-
什麼是 實例方法 :
能被new出來的實例所訪問的方法
-
傳統構造函數定義實例方法的方式:
function Animal (name, age) { this.name = name; this.age = age; } Animal.prototype.sounds = function () { console.log('yayaya') } const a1 = new Animal('dog', 3); a1.sounds()//yayaya
-
class類中,定義實例方法的方式:
class Animal { constructor(name, age){ this.name = name; this.age = age; } sounds () { console.log('yayaya') } } const a2 = new Animal('cat', 2); a2.sounds()//'yayaya'
class內部定義實例方法,與constructor,static平級定義
- 通過控制檯打印 a1 和 a2 可以看到,實例方法都是定義在了原型鏈上,所以兩種方法本質上並沒有區別。
四、使用 static 創建靜態方法(今後用的不多)
- 靜態方法就是掛載到構造函數上的方法,new 出來的 實例 訪問不到;
-
傳統構造函數定義靜態方法的方式:
function Animal (name, age) { this.name = name; this.age = age; } Animal.sounds = function () { console.log('yayaya') } Animal.sounds() //yayaya const a1 = new Animal('dog', 3); a1.sounds()// 報錯:a1.sounds is not a function
-
class類 內部定義靜態方法的方式:
class Animal { constructor(name, age){ this.name = name; this.age = age; } static sounds () { console.log('yayaya') } } Animal.sounds() //yayaya const a2 = new Animal('cat', 2); a2.sounds() // 報錯:a2.sounds is not a function
在class類內部,定義靜態屬性和靜態方法都是通過static關鍵字來修飾的!
注意事項:
- 在class類內部的{ }區間內,只能寫constructor構造器、static靜態方法、static靜態屬性和實例方法(實例屬性在constructor構造器內)!