首先放一段示例代碼
@testable
class MyTestableClass {
// ...
}
function testable(target) {
target.isTestable = true;
}
MyTestableClass.isTestable // true
代碼中@testable即為一個(gè)修飾器??梢钥吹?,修飾器本質(zhì)上是一個(gè)函數(shù)。將類作為修飾器函數(shù)的參數(shù)傳入到函數(shù)內(nèi)部,在函數(shù)內(nèi)部為類掛載了屬性與方法。
除了在類上使用修飾器外,還可以在類內(nèi)部屬性上使用修飾器。示例如下:
class Person {
@readonly
name() { return `${this.first} ${this.last}` }
}
這個(gè)很好理解,表明Person類中的name屬性是只讀的。
那么readonly修飾器函數(shù)是怎樣的呢?
function readonly(target, name, descriptor){
// descriptor對(duì)象原來的值如下
// {
// value: specifiedFunction,
// enumerable: false,
// configurable: true,
// writable: true
// };
descriptor.writable = false;
return descriptor;
}
readonly(Person.prototype, 'name', descriptor);
當(dāng)修飾器作用到類屬性上時(shí),實(shí)則將類原型作為對(duì)象傳入到了修飾器函數(shù)內(nèi)部,第二個(gè)參數(shù)即為作用的類屬性名,第三個(gè)參數(shù)是該屬性的一些默認(rèn)屬性。修改默認(rèn)屬性即可控制該類屬性的一些行為(比如說是否可復(fù)寫該方法等)。
修飾器的兩種使用方法就是上面??這些了。
注意,我們提到修飾器實(shí)則就是一個(gè)函數(shù),所以,遇到React中的這種寫法也就很好理解了
@connect(mapStateToProps, mapDispatchToProps)
function connect(mapStateToProps,mapDispatchToProps){
return function(){}
}