Typescript入門-Day8:物件導向

閱讀時間約 15 分鐘

類別(Class)

在 TypeScript 中,類別(class)是面向對象編程的核心概念。類別用於創建對象,並且可以包含屬性和方法。

建構子(Constructor)

建構子(constructor)是類別的一種特殊方法,用於在創建類別的實例時初始化對象。

class Person {
name: string;
age: number;

constructor(name: string, age: number) {
this.name = name;
this.age = age;
}

greet() {
console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);
}
}

let person = new Person("Alice", 30);
person.greet(); // Hello, my name is Alice and I am 30 years old.

公開(Public)

公開(public)修飾符用於指定類別成員的訪問權限。被標記為 public 的成員可以從類別的內部和外部訪問。

class Animal {
public name: string;

constructor(name: string) {
this.name = name;
}

public move(distance: number): void {
console.log(`${this.name} moved ${distance} meters.`);
}
}

let dog = new Animal("Dog");
dog.move(10); // Dog moved 10 meters.

私有(Private)

私有(private)修飾符用於指定類別成員的訪問權限。被標記為 private 的成員只能在類別的內部訪問。

class Car {
private speed: number;

constructor(speed: number) {
this.speed = speed;
}

public accelerate(): void {
this.speed += 10;
console.log(`Speed is now ${this.speed}`);
}
}

let car = new Car(50);
car.accelerate(); // Speed is now 60
// console.log(car.speed); // Error: Property 'speed' is private and only accessible within class 'Car'.

受保護(Protected)

受保護(protected)修飾符用於指定類別成員的訪問權限。被標記為 protected 的成員只能在類別的內部和其子類別中訪問。

class Employee {
protected id: number;

constructor(id: number) {
this.id = id;
}
}

class Manager extends Employee {
private department: string;

constructor(id: number, department: string) {
super(id);
this.department = department;
}

public getDepartment(): string {
return this.department;
}

public getId(): number {
return this.id;
}
}

let manager = new Manager(1, "HR");
console.log(manager.getDepartment()); // HR
console.log(manager.getId()); // 1

繼承(Inheritance)

繼承是面向對象編程的一個基本概念,通過繼承,一個類別可以從另一個類別獲取屬性和方法。

class Person {
name: string;

constructor(name: string) {
this.name = name;
}

greet() {
console.log(`Hello, my name is ${this.name}`);
}
}

class Employee extends Person {
id: number;

constructor(name: string, id: number) {
super(name);
this.id = id;
}

showId() {
console.log(`My ID is ${this.id}`);
}
}

let employee = new Employee("Alice", 123);
employee.greet(); // Hello, my name is Alice
employee.showId(); // My ID is 123

多型(Polymorphism)

多型允許不同類別的對象以相同的方式做出反應,儘管它們的具體實現不同。

class Shape {
area(): number {
return 0;
}
}

class Circle extends Shape {
radius: number;

constructor(radius: number) {
super();
this.radius = radius;
}

area(): number {
return Math.PI * this.radius * this.radius;
}
}

class Rectangle extends Shape {
width: number;
height: number;

constructor(width: number, height: number) {
super();
this.width = width;
this.height = height;
}

area(): number {
return this.width * this.height;
}
}

let shapes: Shape[] = [new Circle(10), new Rectangle(5, 10)];

shapes.forEach(shape => {
console.log(shape.area());
});
// Output:
// 314.1592653589793
// 50

封裝(Encapsulation)

封裝是將數據和操作數據的方法綁定在一起,並隱藏內部實現細節的一種技術。

class Account {
private balance: number;

constructor(initialBalance: number) {
this.balance = initialBalance;
}

public deposit(amount: number): void {
this.balance += amount;
console.log(`Deposited ${amount}, new balance is ${this.balance}`);
}

public withdraw(amount: number): void {
if (this.balance >= amount) {
this.balance -= amount;
console.log(`Withdrew ${amount}, new balance is ${this.balance}`);
} else {
console.log("Insufficient funds");
}
}

public getBalance(): number {
return this.balance;
}
}

let account = new Account(1000);
account.deposit(500); // Deposited 500, new balance is 1500
account.withdraw(200); // Withdrew 200, new balance is 1300
console.log(account.getBalance()); // 1300

介面(Interface)

介面定義了一個類別必須遵循的結構。它只定義屬性和方法的類型,而不提供具體的實現。

interface Drawable {
draw(): void;
}

class Circle implements Drawable {
draw(): void {
console.log("Drawing a circle");
}
}

class Square implements Drawable {
draw(): void {
console.log("Drawing a square");
}
}

let shapes: Drawable[] = [new Circle(), new Square()];
shapes.forEach(shape => shape.draw());
// Output:
// Drawing a circle
// Drawing a square

抽象類別(Abstract Class)

抽象類別是一種不能被實例化的類別,通常用於定義子類別必須實現的方法。

abstract class Animal {
abstract makeSound(): void;

move(): void {
console.log("Moving...");
}
}

class Dog extends Animal {
makeSound(): void {
console.log("Barking");
}
}

let dog = new Dog();
dog.makeSound(); // Barking
dog.move(); // Moving...

靜態類別(Static Class)

TypeScript 沒有專門的靜態類別,但可以使用靜態成員來實現類似的功能。

class MathUtil {
static PI: number = 3.14159;

static areaOfCircle(radius: number): number {
return MathUtil.PI * radius * radius;
}
}

console.log(MathUtil.areaOfCircle(10)); // 314.159

列舉(Enumerations)

列舉是一種數據類型,用於定義一組命名常數。

enum Color {
Red,
Green,
Blue
}

let color: Color = Color.Green;
console.log(color); // 1

console.log(Color[2]); // Blue

委派(Delegates)

TypeScript 沒有內建的委派,但可以通過函數或接口來實現類似的功能。

interface MathOperation {
(a: number, b: number): number;
}

let add: MathOperation = (a, b) => a + b;
let subtract: MathOperation = (a, b) => a - b;

console.log(add(5, 3)); // 8
console.log(subtract(5, 3)); // 2

Lambda 表達式

Lambda 表達式在 TypeScript 中是通過箭頭函數實現的。

let sum = (a: number, b: number): number => a + b;

console.log(sum(5, 3)); // 8

泛型(Generics)

泛型允許你創建可重用的組件,這些組件可以適用於多種數據類型。

function identity<T>(arg: T): T {
return arg;
}

console.log(identity<number>(5)); // 5
console.log(identity<string>("Hello")); // Hello

反射(Reflection)

TypeScript 中沒有原生的反射機制,但可以通過一些第三方庫來實現。

// 使用 reflect-metadata 庫
import "reflect-metadata";

class Plane {
@Reflect.metadata("role", "transport")
fly() {
console.log("Flying...");
}
}

let plane = new Plane();
let metadataValue = Reflect.getMetadata("role", plane, "fly");
console.log(metadataValue); // transport

13會員
111內容數
日後將分享關於我的經驗(日常、工作、技術),並期待未來能創造屬於我的宇宙。
留言0
查看全部
發表第一個留言支持創作者!
Michael楊 的其他內容
本章節旨在介紹TypeScript中的函數,包括其基本結構、如何呼叫函數、函數的參數以及函數的返回值等相關概念。通過本章節,讀者可以學習到如何在TypeScript中使用不同的方式來定義函數,如函數聲明、函數表達式、箭頭函數和匿名函數等。
本章節提供了關於Typescript中流程控制元素的詳細介紹,包括if, else if, else語句,三元運算子,switch語句,各種for迴圈,while迴圈,循環嵌套和控制迴圈語句(break,continue和標籤)的使用。
此章節旨在介紹TypeScript中的運算符,包括算數運算子、比較運算子、賦值運算子、位元運算子,以及他們的優先等級。每種運算子都以清晰的解釋和代碼範例進行詳細說明,幫助讀者理解並有效地在自己的程式碼中使用。
本章節旨在介紹 TypeScript 的基本資料型別,包括內建型別、型別轉換、自訂型別、元組、集合、陣列、和字典型別。透過理解和使用這些型別,可以提高代碼的可讀性和可維護性。
本章節將引導你如何建立一個TypeScript開發環境,這包括安裝Node.js、npm和TypeScript,建立一個TypeScript項目,設置編輯器,以及編寫和編譯TypeScript代碼。在完成這些步驟之後,你將能夠編寫、編譯和運行TypeScript代碼。
本章節旨在介紹TypeScript的基本語法,包括一般結構、程式進入點、註解以及變數的定義和賦值。這些知識將幫助讀者瞭解TypeScript的基本架構,並且可以開始使用TypeScript進行開發。
本章節旨在介紹TypeScript中的函數,包括其基本結構、如何呼叫函數、函數的參數以及函數的返回值等相關概念。通過本章節,讀者可以學習到如何在TypeScript中使用不同的方式來定義函數,如函數聲明、函數表達式、箭頭函數和匿名函數等。
本章節提供了關於Typescript中流程控制元素的詳細介紹,包括if, else if, else語句,三元運算子,switch語句,各種for迴圈,while迴圈,循環嵌套和控制迴圈語句(break,continue和標籤)的使用。
此章節旨在介紹TypeScript中的運算符,包括算數運算子、比較運算子、賦值運算子、位元運算子,以及他們的優先等級。每種運算子都以清晰的解釋和代碼範例進行詳細說明,幫助讀者理解並有效地在自己的程式碼中使用。
本章節旨在介紹 TypeScript 的基本資料型別,包括內建型別、型別轉換、自訂型別、元組、集合、陣列、和字典型別。透過理解和使用這些型別,可以提高代碼的可讀性和可維護性。
本章節將引導你如何建立一個TypeScript開發環境,這包括安裝Node.js、npm和TypeScript,建立一個TypeScript項目,設置編輯器,以及編寫和編譯TypeScript代碼。在完成這些步驟之後,你將能夠編寫、編譯和運行TypeScript代碼。
本章節旨在介紹TypeScript的基本語法,包括一般結構、程式進入點、註解以及變數的定義和賦值。這些知識將幫助讀者瞭解TypeScript的基本架構,並且可以開始使用TypeScript進行開發。
你可能也想看
Google News 追蹤
Thumbnail
近期的「貼文發佈流程 & 版型大更新」功能大家使用了嗎? 新版式整體視覺上「更加凸顯圖片」,為了搭配這次的更新,我們推出首次貼文策展 ❤️ 使用貼文功能並完成這次的指定任務,還有機會獲得富士即可拍,讓你的美好回憶都可以用即可拍珍藏!
Thumbnail
本文帶你深入探索 TypeScript 中的 satisfies 特性,能幫助你實現精確的型別推導與型別檢查。透過實際案例,展示如何使用 satisfies 提升代碼的型別安全與程式碼的整潔,是每位 TypeScript 開發者不可或缺的知識。
Thumbnail
本文介紹 TypeScript 常遇到的混合型別,以及如何透過五種型別防禦(Type Guard)來解決。涵蓋了使用型別斷言、型別謂詞、in 運算子、typeof 運算子以及 instanceof 運算子這幾種方式。透過本文的學習,能夠更好地運用 TypeScript 進行程式碼開發。
Thumbnail
上一篇文章分享了 TypeScript 的定義、前端角色定位,如果你不是很確定「TypeScript 是什麼?」、「TypeScript 作為 JavaScript 的超集,在網頁開發扮演怎麼樣的角色?」這兩個問題的答案,建議可以回到上一篇先了解一下。
Thumbnail
前言 create react app 是一個可以快速設定 react 專案的一個工具,在建立專案時已經把 babel,webpack 都已經預先封裝設置好,如果我們要修改 webpack alias 設定該如何設定呢 什麼是 alias alias 在 webpack 設定意義叫做,檔案路徑
Thumbnail
自己在剛開始進入前端領域時,很剛好遇上需要使用 TypeScript 的案子,一開始都是跟著前輩怎麼寫就怎麼寫,不太有其他餘力來思考「為什麼」會需要寫這門程式語言,直到自己後來使用了 TypeScript 完整開發了電商的購物流程,才慢慢理解到使用 TypeScript 的好處與優勢。
Thumbnail
Todo App是一個很好學習程式語言的專案開始,JayLin來帶大家手把手用TypeScript | React | TailwildCSS 來做一個小專案
Thumbnail
Typescript: It's not actually validating your types. - DEV Community 👩‍💻👨‍💻 有時他會讓你誤解: 我遇到一個相信 typescript 保證型別就是你說的那樣. 但我必須告訴你: Typescript 不是這樣做的.
Thumbnail
近期的「貼文發佈流程 & 版型大更新」功能大家使用了嗎? 新版式整體視覺上「更加凸顯圖片」,為了搭配這次的更新,我們推出首次貼文策展 ❤️ 使用貼文功能並完成這次的指定任務,還有機會獲得富士即可拍,讓你的美好回憶都可以用即可拍珍藏!
Thumbnail
本文帶你深入探索 TypeScript 中的 satisfies 特性,能幫助你實現精確的型別推導與型別檢查。透過實際案例,展示如何使用 satisfies 提升代碼的型別安全與程式碼的整潔,是每位 TypeScript 開發者不可或缺的知識。
Thumbnail
本文介紹 TypeScript 常遇到的混合型別,以及如何透過五種型別防禦(Type Guard)來解決。涵蓋了使用型別斷言、型別謂詞、in 運算子、typeof 運算子以及 instanceof 運算子這幾種方式。透過本文的學習,能夠更好地運用 TypeScript 進行程式碼開發。
Thumbnail
上一篇文章分享了 TypeScript 的定義、前端角色定位,如果你不是很確定「TypeScript 是什麼?」、「TypeScript 作為 JavaScript 的超集,在網頁開發扮演怎麼樣的角色?」這兩個問題的答案,建議可以回到上一篇先了解一下。
Thumbnail
前言 create react app 是一個可以快速設定 react 專案的一個工具,在建立專案時已經把 babel,webpack 都已經預先封裝設置好,如果我們要修改 webpack alias 設定該如何設定呢 什麼是 alias alias 在 webpack 設定意義叫做,檔案路徑
Thumbnail
自己在剛開始進入前端領域時,很剛好遇上需要使用 TypeScript 的案子,一開始都是跟著前輩怎麼寫就怎麼寫,不太有其他餘力來思考「為什麼」會需要寫這門程式語言,直到自己後來使用了 TypeScript 完整開發了電商的購物流程,才慢慢理解到使用 TypeScript 的好處與優勢。
Thumbnail
Todo App是一個很好學習程式語言的專案開始,JayLin來帶大家手把手用TypeScript | React | TailwildCSS 來做一個小專案
Thumbnail
Typescript: It's not actually validating your types. - DEV Community 👩‍💻👨‍💻 有時他會讓你誤解: 我遇到一個相信 typescript 保證型別就是你說的那樣. 但我必須告訴你: Typescript 不是這樣做的.