日韩成人免费在线_国产成人一二_精品国产免费人成电影在线观..._日本一区二区三区久久久久久久久不

當前位置:首頁 > 科技  > 軟件

TypeScript 裝飾器實用指南!

來源: 責編: 時間:2023-08-09 23:03:20 289觀看
導讀一、裝飾器的概念 Summer IS HERE在 TypeScript 中,裝飾器就是可以添加到類及其成員的函數。TypeScript 裝飾器可以注釋和修改類聲明、方法、屬性和訪問器。Decorator類型定義如下:type Decorator = (target: Input, co

klb28資訊網——每日最新資訊28at.com

一、裝飾器的概念 Summer IS HERE

在 TypeScript 中,裝飾器就是可以添加到類及其成員的函數。TypeScript 裝飾器可以注釋和修改類聲明、方法、屬性和訪問器。Decorator類型定義如下:klb28資訊網——每日最新資訊28at.com

type Decorator = (target: Input, context: {  kind: string;  name: string | symbol;  access: {    get?(): unknown;    set?(value: unknown): void;  };  private?: boolean;  static?: boolean;  addInitializer?(initializer: () => void): void;}) => Output | void;

上面的類型定義解釋如下:klb28資訊網——每日最新資訊28at.com

  • target:代表要裝飾的元素,其類型為 Input。
  • context 包含有關如何聲明修飾方法的元數據,即:
  • kind:裝飾值的類型。正如我們將看到的,這可以是類、方法、getter、setter、字段或訪問器。
  • name:被裝飾對象的名稱。
  • access:引用 getter 和 setter 方法來訪問裝飾對象的對象。
  • private:被裝飾的對象是否是私有類成員。
  • static:被修飾的對象是否是靜態類成員。
  • addInitializer:一種在構造函數開頭(或定義類時)添加自定義初始化邏輯的方法。
  • Output:表示 Decorator 函數返回值的類型。

二、裝飾器的類型 Summer IS HERE

接下來,我們就來了解一下裝飾器的各種類型。klb28資訊網——每日最新資訊28at.com

Summer:類裝飾器

當將函數作為裝飾器附加到類時,將收到類構造函數作為第一個參數:klb28資訊網——每日最新資訊28at.com

type ClassDecorator = (value: Function, context: {  kind: "class"  name: string | undefined  addInitializer(initializer: () => void): void}) => Function | void

例如,假設想要使用裝飾器向 Rocket 類添加兩個屬性:fuel 和 isEmpty()。在這種情況下,可以編寫以下函數:klb28資訊網——每日最新資訊28at.com

function WithFuel(target: typeof Rocket, context): typeof Rocket {  if (context.kind === "class") {    return class extends target {      fuel: number = 50      isEmpty(): boolean {        return this.fuel == 0      }    }  }}

在確保裝飾元素的類型確實是類之后,返回一個具有兩個附加屬性的新類。或者,可以使用原型對象來動態添加新方法:klb28資訊網——每日最新資訊28at.com

function WithFuel(target: typeof Rocket, context): typeof Rocket {  if (context.kind === "class") {    target.prototype.fuel = 50    target.prototype.isEmpty = (): boolean => {      return this.fuel == 0    }  }}

可以按以下方式使用 WithFuel:klb28資訊網——每日最新資訊28at.com

@WithFuelclass Rocket {}const rocket = new Rocket()console.log((rocket as any).fuel)console.log(`empty? ${(rocket as any).isEmpty()}`)/* Prints:50empty? false*/

可以看到,這里將rocket轉換為any類型才能訪問新的屬性。這是因為裝飾器無法影響類型的結構。klb28資訊網——每日最新資訊28at.com

如果原始類定義了一個稍后被裝飾的屬性,裝飾器會覆蓋原始值。例如,如果Rocket有一個具有不同值的fuel屬性,WithFuel裝飾器將會覆蓋該值:klb28資訊網——每日最新資訊28at.com

function WithFuel(target: typeof Rocket, context): typeof Rocket {  if (context.kind === "class") {    return class extends target {      fuel: number = 50      isEmpty(): boolean {        return this.fuel == 0      }    }  }}@WithFuelclass Rocket {  fuel: number = 75}const rocket = new Rocket()console.log((rocket as any).fuel)// 50

Summer:方法裝飾器

方法裝飾器可以用于裝飾類方法。在這種情況下,裝飾器函數的類型如下:klb28資訊網——每日最新資訊28at.com

type ClassMethodDecorator = (target: Function, context: {  kind: "method"  name: string | symbol  access: { get(): unknown }  static: boolean  private: boolean  addInitializer(initializer: () => void): void}) => Function | void

如果希望在調用被裝飾的方法之前或之后執行某些操作時,就可以使用方法裝飾器。klb28資訊網——每日最新資訊28at.com

例如,在開發過程中,記錄對特定方法的調用或在調用之前/之后驗證前置/后置條件可能非常有用。此外,我們還可以影響方法的調用方式,例如通過延遲其執行或限制在一定時間內的調用次數。klb28資訊網——每日最新資訊28at.com

最后,可以使用方法裝飾器將一個方法標記為已廢棄,并記錄一條消息來警告用戶,并告知他們應該使用哪個方法代替:klb28資訊網——每日最新資訊28at.com

function deprecatedMethod(target: Function, context) {  if (context.kind === "method") {    return function (...args: any[]) {      console.log(`${context.name} is deprecated and will be removed in a future version.`)      return target.apply(this, args)    }  }}

在這種情況下,deprecatedMethod函數的第一個參數是要裝飾的方法。確認它確實是一個方法后(context.kind === "method"),返回一個新的函數,該函數在調用實際方法之前包裝被裝飾的方法并記錄一條警告消息。klb28資訊網——每日最新資訊28at.com

接下來,可以按照以下方式使用裝飾器:klb28資訊網——每日最新資訊28at.com

@WithFuelclass Rocket {  fuel: number = 75  @deprecatedMethod  isReadyForLaunch(): Boolean {    return !(this as any).isEmpty()  }}const rocket = new Rocket()console.log(`Is ready for launch? ${rocket.isReadyForLaunch()}`)

在isReadyForLaunch()方法中,引用了通過WithFuel裝飾器添加的isEmpty方法。注意,必須將其轉換為any類型的實例,與之前一樣。當調用isReadyForLaunch()方法時,會看到以下輸出,顯示警告消息被正確地打印出來:klb28資訊網——每日最新資訊28at.com

isReadyForLaunch is deprecated and will be removed in a future version.Is the ready for launch? true

Summer:屬性裝飾器

屬性裝飾器與方法裝飾器的類型非常相似:klb28資訊網——每日最新資訊28at.com

type ClassPropertyDecorator = (target: undefined, context: {  kind: "field"  name: string | symbol  access: { get(): unknown, set(value: unknown): void }  static: boolean  private: boolean}) => (initialValue: unknown) => unknown | void

屬性裝飾器的用例與方法裝飾器的用法也非常相似。例如,可以跟蹤對屬性的訪問或將其標記為已棄用:klb28資訊網——每日最新資訊28at.com

function deprecatedProperty(_: any, context) {  if (context.kind === "field") {    return function (initialValue: any) {      console.log(`${context.name} is deprecated and will be removed in a future version.`)      return initialValue    }  }}

代碼與為方法定義的 deprecatedMethod 裝飾器非常相似,它的用法也是如此。klb28資訊網——每日最新資訊28at.com

Summer:訪問器裝飾器

與方法裝飾器非常相似的是訪問器裝飾器,它是針對 getter 和 setter 的裝飾器:klb28資訊網——每日最新資訊28at.com

type ClassSetterDecorator = (target: Function, context: {  kind: "setter"  name: string | symbol  access: { set(value: unknown): void }  static: boolean  private: boolean  addInitializer(initializer: () => void): void}) => Function | voidtype ClassGetterDecorator = (value: Function, context: {  kind: "getter"  name: string | symbol  access: { get(): unknown }  static: boolean  private: boolean  addInitializer(initializer: () => void): void}) => Function | void

訪問器裝飾器的定義與方法裝飾器的定義類似。例如,可以將 deprecatedMethod 和 deprecatedProperty 修飾合并到一個已棄用的函數中,該函數也支持 getter 和 setter:klb28資訊網——每日最新資訊28at.com

function deprecated(target, context) {  const kind = context.kind  const msg = `${context.name} is deprecated and will be removed in a future version.`  if (kind === "method" || kind === "getter" || kind === "setter") {    return function (...args: any[]) {      console.log(msg)      return target.apply(this, args)    }  } else if (kind === "field") {    return function (initialValue: any) {      console.log(msg)      return initialValue    }  }}

三、裝飾器的用例 Summer IS HERE

上面介紹了裝飾器是什么以及如何正確使用它們,下面來看看裝飾器可以幫助我們解決的一些具體問題。klb28資訊網——每日最新資訊28at.com

Summer:計算執行時間

假設想要估計運行一個函數需要多長時間,以此來衡量應用的性能。可以創建一個裝飾器來計算方法的執行時間并將其打印在控制臺上:klb28資訊網——每日最新資訊28at.com

class Rocket {  @measure  launch() {    console.log("3... 2... 1...  
                

本文鏈接:http://www.www897cc.com/showinfo-26-5177-0.htmlTypeScript 裝飾器實用指南!

聲明:本網頁內容旨在傳播知識,若有侵權等問題請及時與本網聯系,我們將在第一時間刪除處理。郵件:2376512515@qq.com

上一篇: 六款開源、免費的簡歷制作神器,程序員必備!

下一篇: CSS 漸變中的顏色空間和色相插值

標簽:
  • 熱門焦點
Top 主站蜘蛛池模板: 鹤山市| 赤峰市| 仲巴县| 崇文区| 镇平县| 常德市| 南丹县| 昭苏县| 云林县| 都昌县| 扶风县| 通城县| 古浪县| 赤壁市| 莫力| 宜城市| 渭南市| 许昌县| 海门市| 双柏县| 延川县| 获嘉县| 新河县| 东明县| 寿宁县| 乌兰县| 枣强县| 巩义市| 虞城县| 嫩江县| 桂东县| 西和县| 德惠市| 青浦区| 锡林郭勒盟| 华宁县| 溧水县| 马公市| 杭州市| 道孚县| 宿松县|