TS 的裝飾器

官方文檔

https://www.tslang.cn/docs/handbook/decorators.html

什麼是裝飾器

裝飾器是一種特殊的類型聲明,他可以附加在類,方法,屬性,參數上面

類似於java 的註解

注意

要使用TS 的裝飾器的 tsconfig.json,開啓 experimentalDecorators的配置爲true

例:

tsconfig.json:

{
    "compilerOptions": {
        "target": "ES5",
        "experimentalDecorators": true
    }
}

image-20230329164505854

類裝飾器

主要是通過@符號添加裝飾器

他會自動把class的構造函數傳入到裝飾器的第一個參數 target

然後通過prototype可以自定義添加屬性和方法

// 他會自動把class的構造函數傳入到裝飾器的第一個參數 target
function decotators (target:any) {
    // 然後通過prototype可以自定義添加屬性和方法
    target.prototype.name = 'makalo'
}

// 通過@符號添加裝飾器
@decotators
class Makalo {
    // 將構造函數 傳入 decotators 第一個參數
    constructor () {
 
    }
 
}
const makalo:any = new Makalo()
console.log(makalo.name)// makalo

image-20230329165852545

屬性裝飾器

同樣使用@符號給屬性添加裝飾器

他會返回兩個參數

1.原形對象

2.屬性的名稱

// 定義 currency 屬性修飾器
const currency: PropertyDecorator = (target: any, key: string | symbol) => {
    // 返回原型對象和 屬性名
    // Makalo2 {} name
    console.log(target, key)
}
class Makalo2 {
    // 屬性修飾器
    @currency
    public name: string
    constructor() {
        this.name = ''
    }
    getName() {
        return this.name
    }
}

PropertyDecorator 類型描述

image-20230329171556148

參數裝飾器

同樣使用@符號給屬性添加裝飾器

他會返回兩個參數

1.原形對象

2.方法的名稱

3.參數的位置從0開始

const currency3: ParameterDecorator = (target: any, key: string | symbol,index:number) => {
    // Makalo3 {} getName 1
    console.log(target, key,index)
}
 
 
class Makalo3 {
    public name: string
    constructor() {
        this.name = ''
    }
    getName(name:string,@currency3 age:number) {
        return this.name
    }
}

方法裝飾器

同樣使用@符號給屬性添加裝飾器

他會返回兩個參數

1.原形對象

2.方法的名稱

3.屬性描述符 可寫對應writable,可枚舉對應enumerable,可配置對應configurable

const currency4: MethodDecorator = (target: any, key: string | symbol,descriptor:any) => {
    console.log(target, key,descriptor)
}
 
 
class Makalo4 {
    public name: string
    constructor() {
        this.name = ''
    }
    @currency4
    getName(name:string,age:number) {
        return this.name
    }
}

image-20230329172502329

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章