TypeScript装饰器
装饰器被用来修饰类或方法的语法,通过@来调用,装饰器目前还处在测试阶段,开启typescript中的装饰器需要在tsconfig.json中额外配置一下
// 启用装饰器
"experimentalDecorators": true,
"emitDecoratorMetadata": true
1. 类装饰器
function Component(constructor: Function){
console.log('Component decorator called')
constructor.prototype.uniqueId = Date.now();
constructor.prototype.insertInDom = () => {
console.log('inerting the component in the DOM');
}
}
@Component
class Profile{}
// 注意装饰器并不是在创建实例时调用,而是在声明时就会被调用
2. 参数化装饰器
type ComponentOptions = {
selector: string
}
function Component(options: ComponentOptions) {
return (constructor: Function) => {
console.log('Component decorator called')
constructor.prototype.options = options;
constructor.prototype.insertInDom = () => {
console.log('inerting the component in the DOM');
}
}
}
@Component({selector: "#my-profile"})
class ProfileComponent {}