TypeScript面向对象编程

2023-10-05  本文已影响0人  杨志聪

面向对象编程是编程风格的一种,以对象为基本材料来构建应用程序。对象可以包含数据(属性)和逻辑(方法)。

类和对象

类是创建对象的蓝图。

class Account {
  id: number;
  // 构造方法(constructor)是一个类里面的一个特殊的方法
  // 构造方法会在创建一个实例时被调用
  // 我们在构造方法中初始化属性
  constructor(id: number) { 
      this.id = id;
  }
 }

let account = new Account(1);

访问控制修饰符(Access Modifiers)

有三种访问控制修饰符:public, private和protected。public是默认的修饰符。private和protected的成员都不能被外部访问,但是protected的成员可以被继承,private的成员不能被继承。一般很少会用protected,除非你真的很清楚你要做什么。

class Account {
  // protected的属性可以被继承
  // private的属性不能被继承
  private _balance: number;
  protected _taxRate: number;
}

可选属性和只读属性

class Account {
    // 只读属性
    readonly id: number;
    // 可选属性
    nickname?: string;
    constructor(id: number) {
        this.id = id;
    }
}

参数属性(Parameter Properties)

参数属性(Parameter Properties)允许将构造函数参数直接声明为类的属性。这种语法糖减少了代码的冗余,使得代码更加简洁和清晰。

class Account {
  constructor(public id: number, private _balance: number) {}
}

let a = new Account(1, 100);
console.log(a.id);

getter和setter

getter和setter特性允许我们在读取或者写入属性时,有机会做一些逻辑判断。

class Account {
  constructor(private _balance: number) {}
  get balance() {
    return this._balance;
  }
  set balance(balance: number) {
    if (balance < 0) throw "Invalid balance!";
    this._balance = balance;
  }
}

let a = new Account(100);
a.balance = -1;

索引签名(Index Signatures)

通过索引签名(Index Signatures)可以动态地为一个对象添加属性,同时可以保证类型安全:

class SeatAssignment {
  [seatNumber: string]: string;
}
let seats = new SeatAssignment();
seats.A1 = "Mary";
seats.A2 = "John";

静态方法和属性

class Account {
    static count = 0;
    static foo() {
    }
}

Account.count++;
Account.foo();

继承

class Student extends Person {
}

方法重写(Method Overriding)

class Student extends Person {
  override speak() {
    console.log("Student speaking");
  }
}

抽象类和抽象方法

抽象类,是“不完整”的类。抽象类不能用来实例化对象,需要被继承,在子类中完成完整的类,才能用来实例化对象。

abstract class Shape {
  // 抽象方法不需要写函数体,而且用分号结尾
  abstract render();
}
class Circle extends Shape {
  override render() {
    console.log("Rendering a circle");
  }
}

接口(interface)

我们用接口来定义一个对象的形状。

interface Calendar {
  name: string;
  addEvent(): void;
}
class GoogleCalendar implements Calendar {
    constructor(public name: string) {}
    addEvent(): void {
        
    }
}

Interface VS Type

在TypeScript中,interface和type可以互换使用。

它们都能描述一个对象的形状。

使用type:

type Person = {
  name: string;
};
let tom: Person = { name: "tom" };

使用interface:

interface Person {
  name: string;
}
let tom: Person = { name: "tom" };

它们都能被一个类实现。

使用type:

type Person = {
  name: string;
};

class Student implements Person {
  constructor(public name: string) {}
}

使用interface:

interface Person {
  name: string;
}

class Student implements Person {
  constructor(public name: string) {}
}
上一篇 下一篇

猜你喜欢

热点阅读