TypeScript面向?qū)ο?/h2>

TypeScript面向?qū)ο?/h1>

readonly

單層修飾只讀屬性。

構(gòu)造器

構(gòu)造方法。

方法

Getters/Setters

類里面的特殊方法,稱之為訪問器。
同名的方法,不同的關(guān)鍵字修飾。

class C {
    _length: number = 0

    get length() {
        return this._length
    }

    set length(value: number) {
        this._length = value
    }
}

部分特殊規(guī)則:

  • 如果存在get,但沒有set,則該屬性自動是只讀的。
  • 如果沒有制定setter參數(shù)的類型,它將從getter的返回類型中推斷出來。
  • 訪問器和設(shè)置器必須有相同成員的可見性。

索引簽名

class MyClass {
    [s: string]: boolean | ((s: string) => boolean)

    x = true

    check(s: string) {
        return this[s] as boolean
    }
}

類的繼承

implement子句

interface Pingable { // 接口
    ping(): void
}

class Sonar implements Pingable { // 實(shí)現(xiàn)
    ping() {
        console.log("ping!")
    }
}

可以實(shí)現(xiàn)多個(gè)接口,implements后面用逗號連接。

interface A {}
interface B {}

class C implements A, B {
    
}

extends子句

子類可獲得父類所有方法。

class Animal { // 基類
    // ...
}

class Dog extends Animal { // 派生類
    // ...
}

初始化順序

class Base {
    name = "base"

    constructor() {
        console.log("My name is " + this.name)
    }
}

class Derived extends Base {
    name = "derived"
}

const d = new Derived()

順序:

  1. 基類的字段被初始化
  2. 基類構(gòu)造函數(shù)運(yùn)行
  3. 派生類的字段被初始化
  4. 派生類構(gòu)造函數(shù)運(yùn)行

繼承內(nèi)置類型

編譯的目標(biāo)對象版本會影響運(yùn)行結(jié)果,使用es6以上版本不必過于關(guān)心。

class MsgError extends Error {
    constructor(s: string) {
        super(s)
    }

    sayHello() {
        return "hello " + this.message
    }
}

類成員的可見性

  • public: 公開的,默認(rèn)值。任何對象在任何對方都可以訪問。
  • protected:受保護(hù)的。能在當(dāng)前類或者子類中進(jìn)行訪問。
  • private: 私有的。只能在當(dāng)前類中進(jìn)行訪問。

類的靜態(tài)成員

可以使用類名直接調(diào)用。

class MyClass {
    static x = 0
    static printX() {
        console.log(MyClass.x)
    }
}

注意:
特殊的靜態(tài)名稱不安全,避免使用:name,length,call等。
TypeScript沒有靜態(tài)類的概念,因?yàn)槲覀冞€有函數(shù)和普通對象。

static模塊

class Foo {
    static #count = 0

    get count() {
        return Foo.#count
    }

    static { // static塊 ,訪問性:私有的
        Foo.#count += lastInstances.length
    }
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容