Week 02 · Day 05 — TypeScript 類別
學習目標
- 學會用
class建立物件藍圖 - 認識建構子、屬性與方法
- 理解
public/private修飾詞與constructor簡寫
重點
基本類別
class Animal {
constructor(public name: string) {}
// ^^^^^^^^^ 參數屬性簡寫:自動建立並指派 this.name
speak(): string {
return `${this.name} makes a sound`;
}
}
建構子(constructor)
- 物件的初始化方法,new Animal("Bob") 時被呼叫
- public name: string 在參數中 = 自動宣告公開屬性並指派,等同:
class Animal {
name: string;
constructor(name: string) {
this.name = name;
}
}
屬性修飾詞
- public:任何地方都可存取(預設)
- private:只有類別內部可存取
- protected:類別本身與子類別可存取
使用
const a = new Animal("Kiki");
console.log(a.name); // Kiki
console.log(a.speak()); // Kiki makes a sound
實作
class Car {
constructor(public brand: string, private speed = 0) {}
accelerate(by: number): void {
this.speed += by;
}
describe(): string {
return `${this.brand} at ${this.speed} km/h`;
}
}
const car = new Car("Toyota");
car.accelerate(30);
console.log(car.describe()); // Toyota at 30 km/h
// car.speed; // ❌ private 無法從外部存取
作業
- 建立一個類別,使用
constructor(public ...)簡寫 - 至少含一個私有屬性與一個公開方法
- 說出
public與private的差別