1、修飾器對類的行為的改變,是代碼編譯時發生的,而不是在運行時。這意味着,修飾器能在編譯階段運行代碼。
2、
function testable(target) { target.isTestable = true; } @testable class MyTestableClass {} console.log(MyTestableClass.isTestable) // true
上面代碼中,@testable
就是一個修飾器。它修改了MyTestableClass
這個類的行為,為它加上了靜態屬性isTestable
。
3、修飾器不僅可以修飾類,還可以修飾類的屬性。
class Person { @readonly name() { return `${this.first} ${this.last}` } }
上面代碼中,修飾器readonly
用來修飾“類”的name
方法。
此時,修飾器函數一共可以接受三個參數,第一個參數是所要修飾的目標對象,第二個參數是所要修飾的屬性名,第三個參數是該屬性的描述對象。
function readonly(target, name, descriptor){ // descriptor對象原來的值如下 // { // value: specifiedFunction, // enumerable: false, // configurable: true, // writable: true // }; descriptor.writable = false; return descriptor; } readonly(Person.prototype, 'name', descriptor); // 類似於 Object.defineProperty(Person.prototype, 'name', descriptor);
4、修飾器只能用於類和類的方法,不能用於函數,因為存在函數提升。類是不會提升的,所以就沒有這方面的問題。