什么是裝飾器
裝飾器是一種特殊類型的聲明,它能夠被附加到類聲明,方法, 訪問符,屬性或參數上。 裝飾器使用 @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
從上述例子得出如下結論:
有多個參數裝飾器時:從最后一個參數依次向前執行
方法和方法參數中參數裝飾器先執行。
類裝飾器總是最后執行。
方法和屬性裝飾器,誰在前面誰先執行。因為參數屬于方法一部分,所以參數會一直緊緊挨著方法執行。
上述例子中屬性和方法調換位置,輸出如下結果:
I am parameter2 decorator
I am parameter1 decorator
I am method decorator
I am property decorator
I am class decorator