類就是用來創造對象的東西。它和interface的區別是:interface實現了class的一部分功能,class是interface的高配版本(個人理解),對於使用過 TS 的 JS 程序員來說,類可以讓你的系統更加「可預測」這個對象不會出現一些我不知道的屬性,一切都盡在我的掌握。
### 語法
- 聲明類(class)
- 聲明對象的非函數屬性
- 聲明對象的函數屬性
- 使用 constructor
- 聲明類的屬性(static)指的是class的靜態屬性,static申明的屬性屬於class的,不屬於實例的的屬性
- 使用 this 代指當前對象(注意不要以為 this 永遠都代指當前對象,JS 的 this 有更多功能,而且默認 this 為 window)
### 類繼承類
使用 super
~~~js
class A{
type:string;
constructor(type:string){
this.type = type
}
}
class B extends A {
constroctor(){
super('xxx')
}
}
const b = new B()
console.log(b) // { type: 'xxx' }
~~~
### 修飾符
public : 默認的屬性都是public 的
private :私有屬性 不能在在實例化后的實例中使用這個屬性 , 只能在class中共創建使用 類似於局部變量
protected :只能在自己和子代中使用的屬性,實例中不會顯示此屬性
### 訪問器
get 和 set
###