在tsconfig.json 里compilerOptions中配置
experimentalDecorators: true
创建一个class Decorators
function Logger(constructor: Function){
console.log('this is logger')
}
@Logger
class Person {
name: string = 'max';
constructor(){
console.log('this is person constructor')
}
}
const person = new Person()
output:
"this is logger"
"this is person constructor"
Logger 在class定义的时候执行,在创建一个实例前执行。一般第一个字母大写,需要接收参数
Decorators factory
function Logger(logString: string){
return function(constructor: Function){
console.log(logString)
console.log(constructor)
}
}
@Logger("Logger-Person")
class Person {
name: string = 'max';
constructor(){
console.log('this is person constructor')
}
}
const person = new Person()
output
[LOG]: "Logger-Person"
[LOG]: class Person {
constructor() {
this.name = 'max';
console.log('this is person constructor');
}
}
[LOG]: "this is person constructor"
插入html代码
function WithTemplate(template: string, bookId: string){
return function(constructor: any) {
const bookEle = document.getElementById(bookId) as HTMLElement
// new constructor() 实例化
const p = new constructor();
console.log(p.name)
if(bookEle) {
bookEle.innerHTML = template
}
}
}
@WithTemplate('<h1>it is a book</h1>', 'bookId')
class Book {
name = 'good'
constructor(){
console.log('this is book')
}
}
const book = new Book()
添加多个Decorators
function Logger(){
console.log("logger factory")
return function(constructor: Function){
console.log("logger function")
}
}
function WithTemplate(){
console.log("template factory")
return function(constructor: any) {
console.log("template function")
}
}
@Logger()
@WithTemplate()
class Book {
constructor(){
console.log('this is book')
}
}
const book = new Book()
output:
[LOG]: "logger factory"
[LOG]: "template factory"
[LOG]: "template function"
[LOG]: "logger function"
[LOG]: "this is book"
多个decorators, factory 从外到里运行, function从里到外执行。
创建一个Property Decorators
function Log(target:any, propertyName: string){
console.log(target)
console.log(propertyName)
}
class Product {
@Log
title: string;
private _price: number;
constructor(t: string, p: number){
this.title = t;
this._price = p
}
set price(val: number) {
if(val > 0) {
this._price = val
}else {
throw new Error('this is invalid')
}
}
getPriceWithTax(tax: number) {
return this._price *( 1+ tax)
}
}
网友评论