typescript和Es6的class區(qū)別?【專欄10】

TypeScript是ES6的超集。至于需不需要使用,在于你所需要的場景。
相同點
都是采用extends語法進行繼承 在constructor中都需要首先使用super()調(diào)用父類構(gòu)造函數(shù),然后才能獲取父類的屬性 最終都是通過ES5的原型鏈進行繼承
不同點
typescript class中有屬性字段有private、protected、readonly等修飾符 typescript constructor構(gòu)造函數(shù)參數(shù)必須定義所屬類型 typescript class中可以存著靜態(tài)方法 typescript class方法參數(shù)會類型驗證 es6中, 只有靜態(tài)方法,沒有靜態(tài)屬性。
public 共有的。類的內(nèi)外都可以使用。 protected 受保護的。類的內(nèi)部使用,繼承的子類中使用。 private 私有的。類的內(nèi)部使用。
ES6
class UserBase {
constructor (color) {
this.color = color;
}
static showColor () {
//color ==>undefined
console.log(`我是一個有顏色的公有靜態(tài)函數(shù),看看我的顏色${this.color}`)
}
}
class User extends UserBase {
constructor (userName, userAge) {
super("yellow");
this.userName=userName;
this.userAge=userAge;
}
showInfo(){
console.log(`名字${this.userName}今年:${this.userAge}`)
}
}
const user=new User("鬼鬼",18);
user.showInfo();//實例函數(shù)
User.showColor()//靜態(tài)函數(shù)
typescript
class UserBase{
static color="yellow";//靜態(tài)屬性
static showColor() {//靜態(tài)方法
console.log(`我是一個有顏色的公有靜態(tài)函數(shù),看看我的顏色${this.color}`)
}
}
class User extends UserBase{
private userName: string;
private userAge: number;
constructor(userName : string,userAge:number){
super();//必須調(diào)用super才能繼承showColor函數(shù)
this.userName=userName;
this.userAge=userAge;
}
private showInfo ():void{
console.log(`名字${this.userName}今年:${this.userAge}`)
}
}
const user=new User("鬼鬼",18);
user.showInfo();//實例函數(shù)
User.showColor();//靜態(tài)函數(shù)說明
本專欄總共匯總了
150道題,每道題目答案沒有多余扯皮的部分,就是單純的答案。關(guān)注公眾號,每天一到面試題,為下次跳槽準備,人人都能沖擊
30k+,點擊↓關(guān)注【鬼哥】當前進度【#010題】,如果你能點贊分享、鬼哥騎自行車也是開心的
評論
圖片
表情
