TypeScript 類的裝飾器


// 類的裝飾器:對類的一個修飾

/**
* 裝飾器本身是一個函數
* @param constructor
* 類的裝飾器接收的函數是類的構造函數 constructor
*
* testDecorator 的運行時機是類創建的時候立即執行
* 對類做修飾,不是對實例做修飾
*/
function testDecorator(constructor: any) {
  constructor.prototype.getName = () => {
    console.log('dell');
  }
  console.log('decorator');
}
// 裝飾器可以寫多個
function testDecorator1(constructor: any) {
  console.log('decorator1');
}


/**
* 裝飾器通過 @ 符號來使用
* 如果報錯,不支持使用,打開 tsconfig.json 這兩個配置項
* experimentalDecorators,emitDecoratorMetadata
*
* 多個裝飾器的時候,執行的時候是從下到上,從右到左
*/
@testDecorator @testDecorator1
class Test{ }

const test = new Test();
(test as any).getName();

 




有的時候我希望去使用 testDecorator 對類裝飾,有的時候不希望對類裝飾
// 最外層是個函數,再返回一個新的函數
function testDecorator(flag: boolean) {
  if (flag) {
    return function (constructor: any) {
      constructor.prototype.getName = () => {
        console.log('dell');
      }
    }
  } else {
    return function (constructor: any) { }
  }
}

// 執行下這個函數,跟上面不包含的效果是一樣 的
@testDecorator(true)
class Test{ }

const test = new Test();
(test as any).getName();

傳 true ,會調用類的裝飾器,傳 false 報錯


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM