1. 程式人生 > 實用技巧 >typeScript 類

typeScript 類

  1. 重寫和過載的的區分:
    重寫是存在類與類之間的;過載沒有沒有類與類之間的說法,比如同一個類裡面方法名字相同,但是他們的引數不同(包括引數的順序不同)。通過傳入的引數不同匹配相應的方法。
// 重寫
class Animal{
  move(){
    console.log('animal can move')
  }
}
class Snack extends Animal{
  move(){
    console.log('snack can move')
  }
  black(){
    console.log('snack is black')
  }
}
const snack = new Snack();
snack.move()  // snack can move
  1. 派生類包含了建構函式,必須呼叫super(),super()它會執行基類的建構函式。 而且,在建構函式裡訪問 this的屬性之前,我們 一定要呼叫 super()。
  2. 修飾符public, private, protected,readonly區別:
    • 預設是 public,
    • private:當成員被標記成 private時,它只能在它宣告的類{}裡面使用。它就不能在宣告它的類的外部訪問。

      一般的用法是:
class Animal {
  private name: string;
  constructor(theName: string) { this.name = theName; }
  getName(){
    return this.name
  }
  setName(name: string){
    this.name = name
  }
}

class Rhino extends Animal {
  constructor() { super("Rhino");}
}

class Employee {
  private name: string;
  constructor(theName: string) { this.name = theName; }
}

const animal = new Animal("Goat");
animal.setName('dog');
console.log(animal.getName()); // dog
let rhino = new Rhino();
let employee = new Employee("Bob");
  • protected成員在它宣告的類{}中和派生類{}中可以訪問。例如:
class Person{
  protected name: string;
  constructor(name: string){
    this.name = name;
  }
}

class Emplyee extends Person{
  constructor(name: string){
    super(name)
  }
  public getSalaryValue(money: number){
    console.log(`${this.name} get money$ ${money}`)
  }
}
const person = new Person('person');
const emplyee = new Emplyee('sandy');

emplyee.getSalaryValue(100000000) // sandy get money$ 100000000
person.name //Error: 屬性“name”受保護,只能在類“Person”及其子類中訪問。

*建構函式也可以被標記成 protected。 這意味著這個類不能在包含它的類外被例項化,但是能被繼承。

class Person {
    protected name: string;
    protected constructor(theName: string) { this.name = theName; }
}

// Employee 能夠繼承 Person
class Employee extends Person {
    private department: string;

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

    public getElevatorPitch() {
        return `Hello, my name is ${this.name} and I work in ${this.department}.`;
    }
}

let howard = new Employee("Howard", "Sales");
let john = new Person("John"); // 錯誤: 'Person' 的建構函式是被保護的.
  • 你可以使用 readonly關鍵字將屬性設定為只讀的。 只讀屬性必須在宣告時或建構函式裡被初始化。
class Octopus {
    readonly name: string;
    readonly numberOfLegs: number = 8;
    constructor (theName: string) {
        this.name = theName;
    }
}
let dad = new Octopus("Man with the 8 strong legs");
dad.name = "Man with the 3-piece suit"; // 錯誤! name 是隻讀的.