TypeScript裝飾器(decorators)

什么是裝飾器

裝飾器是一種特殊類型的聲明,它能夠被附加到類聲明,方法, 訪問符,屬性或參數上。 裝飾器使用 @expression這種形式,expression求值后必須為一個函數,它會在運行時被調用,被裝飾的聲明信息做為參數傳入。

通俗的理解可以認為就是在原有代碼外層包裝了一層處理邏輯。
個人認為裝飾器是一種解決方案,而并非是狹義的@Decorator,后者僅僅是一個語法糖罷了。

裝飾器在身邊的例子隨處可見,一個簡單的例子

水龍頭上邊的起泡器就是一個裝飾器,在裝上以后就會把空氣混入水流中,摻雜很多泡泡在水里。
但是起泡器安裝與否對水龍頭本身并沒有什么影響,即使拆掉起泡器,也會照樣工作,水龍頭的作用在于閥門的控制,至于水中摻不摻雜氣泡則不是水龍頭需要關心的。

在TypeScript中裝飾器還屬于實驗性語法,你必須在命令行或tsconfig.json里啟用experimentalDecorators編譯器選項:

命令行:

tsc --target ES5 --experimentalDecorators

tsconfig.json:

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

為什么要用裝飾器

可能有些時候,我們會對傳入參數的類型判斷、對返回值的排序、過濾,對函數添加節流、防抖或其他的功能性代碼,基于多個類的繼承,各種各樣的與函數邏輯本身無關的、重復性的代碼。
所以,對于裝飾器,可以簡單地理解為是非侵入式的行為修改。

如何定義裝飾器

裝飾器本身其實就是一個函數,理論上忽略參數的話,任何函數都可以當做裝飾器使用。
helloword.ts

function helloWord(target: any) {
    console.log('hello Word!');
}

@helloWord
class HelloWordClass {

}

使用tsc編譯后,執行命令node helloword.js,輸出結果如下:

hello Word!

裝飾器組合
多個裝飾器可以同時應用到一個聲明上,就像下面的示例:

書寫在同一行上:

@f @g x

書寫在多行上:

@f
@g
x

裝飾器執行時機

修飾器對類的行為的改變,是代碼編譯時發生的(不是TypeScript編譯,而是js在執行機中編譯階段),而不是在運行時。這意味著,修飾器能在編譯階段運行代碼。也就是說,修飾器本質就是編譯時執行的函數。
在Node.js環境中模塊一加載時就會執行

但是實際場景中,有時希望向裝飾器傳入一些參數, 如下:

@Path("/hello", "world")
class HelloService {}

此時上面裝飾器方法就不滿足了(VSCode編譯報錯),這是我們可以借助JavaScript中函數柯里化特性

function Path(p1: string, p2: string) {
    return function (target) { //  這才是真正裝飾器
        // do something 
    }
}

裝飾器類型

裝飾器的類型有:類裝飾器、訪問器裝飾器、屬性裝飾器、方法裝飾器、參數裝飾器,但是沒有函數裝飾器(function)。

1.類裝飾器

應用于類構造函數,其參數是類的構造函數。
注意class并不是像Java那種強類型語言中的類,而是JavaScript構造函數的語法糖。

function addAge(args: number) {
    return function (target: Function) {
        target.prototype.age = args;
    };
}

@addAge(18)
class Hello {
    name: string;
    age: number;
    constructor() {
        console.log('hello');
        this.name = 'yugo';
    }
}

console.log(Hello.prototype.age);//18
let hello = new Hello();

console.log(hello.age);//18

2.方法裝飾器

它會被應用到方法的 屬性描述符上,可以用來監視,修改或者替換方法定義。
方法裝飾會在運行時傳入下列3個參數:

  • 1、對于靜態成員來說是類的構造函數,對于實例成員是類的原型對象。
  • 2、成員的名字。
  • 3、成員的屬性描述符{value: any, writable: boolean, enumerable: boolean, configurable: boolean}。
function addAge(constructor: Function) {
  constructor.prototype.age = 18;
}
?
function method(target: any, propertyKey: string, descriptor: PropertyDescriptor) {
   console.log(target);
   console.log("prop " + propertyKey);
   console.log("desc " + JSON.stringify(descriptor) + "\n\n");
};
?
@addAge
class Hello{
  name: string;
  age: number;
  constructor() {
    console.log('hello');
    this.name = 'yugo';
  }
?
  @method
  hello(){
    return 'instance method';
  }
?
  @method
  static shello(){
    return 'static method';
  }
}

我們得到的結果是

Hello { hello: [Function] }
prop hello
desc {"writable":true,"enumerable":true,"configurable":true}
?
?
{ [Function: Hello] shello: [Function] }
prop shello
desc {"writable":true,"enumerable":true,"configurable":true}

假如我們修飾的是 hello 這個實例方法,第一個參數將是原型對象,也就是 Hello.prototype。

假如是 shello 這個靜態方法,則第一個參數是構造器 constructor。

第二個參數分別是屬性名,第三個參數是屬性修飾對象。

注意:在vscode編輯時有時會報作為表達式調用時,無法解析方法修飾器的簽名。錯誤,此時需要在tsconfig.json中增加target配置項:

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

3. 訪問器裝飾器

訪問器裝飾器應用于訪問器的屬性描述符,可用于觀察,修改或替換訪問者的定義。 訪問器裝飾器不能在聲明文件中使用,也不能在任何其他環境上下文中使用(例如在聲明類中)。

注意: TypeScript不允許為單個成員裝飾get和set訪問器。相反,該成員的所有裝飾器必須應用于按文檔順序指定的第一個訪問器。這是因為裝飾器適用于屬性描述符,它結合了get和set訪問器,而不是單獨的每個聲明。

訪問器裝飾器表達式會在運行時當作函數被調用,傳入下列3個參數:

  • 對于靜態成員來說是類的構造函數,對于實例成員是類的原型對象。
  • 成員的名字。
  • 成員的屬性描述符。

注意? 如果代碼輸出目標版本小于ES5,Property Descriptor將會是undefined。

如果訪問器裝飾器返回一個值,它會被用作方法的屬性描述符。

注意? 如果代碼輸出目標版本小于ES5返回值會被忽略。

下面是使用了訪問器裝飾器(@configurable)的例子,應用于Point類的成員上:

 class Point {
    private _x: number;
    private _y: number;
    constructor(x: number, y: number) {
        this._x = x;
        this._y = y;
    }

    @configurable(false)
    get x() { return this._x; }

    @configurable(false)
    get y() { return this._y; }
}

我們可以通過如下函數聲明來定義@configurable裝飾器:

function configurable(value: boolean) {
    return function (target: any, propertyKey: string, descriptor: PropertyDescriptor) {
        descriptor.configurable = value;
    };
}

4. 方法參數裝飾器

參數裝飾器表達式會在運行時當作函數被調用,傳入下列3個參數:

  • 1、對于靜態成員來說是類的構造函數,對于實例成員是類的原型對象。
  • 2、參數的名字。
  • 3、參數在函數參數列表中的索引。
const parseConf = [];
class Modal {
    @parseFunc
    public addOne(@parse('number') num) {
        console.log('num:', num);
        return num + 1;
    }
}

// 在函數調用前執行格式化操作
function parseFunc(target, name, descriptor) {
    const originalMethod = descriptor.value;
    descriptor.value = function (...args: any[]) {
        for (let index = 0; index < parseConf.length; index++) {
            const type = parseConf[index];
            console.log(type);
            switch (type) {
                case 'number':
                    args[index] = Number(args[index]);
                    break;
                case 'string':
                    args[index] = String(args[index]);
                    break;
                case 'boolean':
                    args[index] = String(args[index]) === 'true';
                    break;
            }
            return originalMethod.apply(this, args);
        }
    };
    return descriptor;
}

// 向全局對象中添加對應的格式化信息
function parse(type) {
    return function (target, name, index) {
        parseConf[index] = type;
        console.log('parseConf[index]:', type);
    };
}
let modal = new Modal();
console.log(modal.addOne('10')); // 11

5. 屬性裝飾器

屬性裝飾器表達式會在運行時當作函數被調用,傳入下列2個參數:

  • 1、對于靜態成員來說是類的構造函數,對于實例成員是類的原型對象。
  • 2、成員的名字。
function log(target: any, propertyKey: string) {
    let value = target[propertyKey];
    // 用來替換的getter
    const getter = function () {
        console.log(`Getter for ${propertyKey} returned ${value}`);
        return value;
    }
    // 用來替換的setter
    const setter = function (newVal) {
        console.log(`Set ${propertyKey} to ${newVal}`);
        value = newVal;
    };
    // 替換屬性,先刪除原先的屬性,再重新定義屬性
    if (delete this[propertyKey]) {
        Object.defineProperty(target, propertyKey, {
            get: getter,
            set: setter,
            enumerable: true,
            configurable: true
        });
    }
}
class Calculator {
    @log
    public num: number;
    square() {
        return this.num * this.num;
    }
}
let cal = new Calculator();
cal.num = 2;
console.log(cal.square());
// Set num to 2
// Getter for num returned 2
// Getter for num returned 2
// 4

裝飾器加載順序

function ClassDecorator() {
    return function (target) {
        console.log("I am class decorator");
    }
}
function MethodDecorator() {
    return function (target, methodName: string, descriptor: PropertyDescriptor) {
        console.log("I am method decorator");
    }
}
function Param1Decorator() {
    return function (target, methodName: string, paramIndex: number) {
        console.log("I am parameter1 decorator");
    }
}
function Param2Decorator() {
    return function (target, methodName: string, paramIndex: number) {
        console.log("I am parameter2 decorator");
    }
}
function PropertyDecorator() {
    return function (target, propertyName: string) {
        console.log("I am property decorator");
    }
}

@ClassDecorator()
class Hello {
    @PropertyDecorator()
    greeting: string;


    @MethodDecorator()
    greet( @Param1Decorator() p1: string, @Param2Decorator() p2: string) { }
}

輸出結果:

I am property decorator
I am parameter2 decorator
I am parameter1 decorator
I am method decorator
I am class decorator

從上述例子得出如下結論:

  1. 有多個參數裝飾器時:從最后一個參數依次向前執行

  2. 方法和方法參數中參數裝飾器先執行。

  3. 類裝飾器總是最后執行。

  4. 方法和屬性裝飾器,誰在前面誰先執行。因為參數屬于方法一部分,所以參數會一直緊緊挨著方法執行。

上述例子中屬性和方法調換位置,輸出如下結果:

I am parameter2 decorator
I am parameter1 decorator
I am method decorator
I am property decorator
I am class decorator
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 228,030評論 6 531
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 98,310評論 3 415
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事?!?“怎么了?”我有些...
    開封第一講書人閱讀 175,951評論 0 373
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 62,796評論 1 309
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 71,566評論 6 407
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 55,055評論 1 322
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,142評論 3 440
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 42,303評論 0 288
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 48,799評論 1 333
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 40,683評論 3 354
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 42,899評論 1 369
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,409評論 5 358
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 44,135評論 3 347
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,520評論 0 26
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 35,757評論 1 282
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 51,528評論 3 390
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 47,844評論 2 372

推薦閱讀更多精彩內容