美文网首页
Typescript修饰器

Typescript修饰器

作者: 梦安web开发 | 来源:发表于2023-11-03 22:22 被阅读0次

装饰器是一种特殊类型的声明,它能够被附加到类声明,方法,访问,属性或参数上。 装饰器使用 @expression这种形式,expression求值后必须为一个函数,它会在运行时被调用,被装饰的声明信息做为参数传入。
装饰器应用有以下几种方式

  • 类装饰器
  • 装饰器工厂
  • 装饰器组合
  • 属性装饰器
  • 方法装饰器

项目使用装饰器前,必须在命令行或tsconfig.json里启用experimentalDecorators编译器选项:
命令行:

tsc --target ES5 --experimentalDecorators

tsconfig.json:

{
    "compilerOptions": {
        "target": "ES5",
        "experimentalDecorators": true
    }
}

类装饰器

function fun(target:any){
      target.prototype.name='zhang';
      target.age=19;
}
@fun  // @fun==@fun(Person)
class Person{

}
let p1=new Person();
console.log(p1.name);//zhang
console.log(Person.age);//19

装饰器工厂

如果我们想自定义如何将装饰器应用于声明,我们可以编写一个装饰器工厂。装饰器工厂只是一个函数,它返回将由装饰器在运行时调用的表达式。

我们可以用以下方式编写一个装饰器工厂:

function color(value: string) {
  // this is the decorator factory, it sets up
  // the returned decorator function
  return function (target) {
    // this is the decorator
    // do something with 'target' and 'value'...
  };
}

function fun2(options:any){
  return function (target:any){
    target.prototype.username=options.name;
    target.prototype.userage=options.age
  }

}

@fun2({
  name:"张三",
  age:17
})
class Person2{

}
let p2=new Person2();
//@ts-ignore
console.log(p2.userage)//17

装饰器组合

可以将多个装饰器应用于声明,例如在一行中:

function f() {}
function g() {}
@f @g x

属性装饰器

function fun3(arg:any){
  return function (target:any,attr:any){
    target[attr]=arg;
  }
}

class Person2{
   @fun3('zhangsan')
   userName:string
}
let p2=new Person2();
//@ts-ignore
console.log(p2.userName)//zhangsan

方法装饰器

function test(target:any,propertyKey:string,descriptos:PropertyDescriptor){
    console.log(targer) //类Person
    console.log(propertyKey)方法名
}

class Person{
   @test
   sayName(){
     console.log("say name...")
    }
}
let p=new Person();
//@ts-ignore
p.sayName()

相关文章

网友评论

      本文标题:Typescript修饰器

      本文链接:https://www.haomeiwen.com/subject/gunvedtx.html