装饰器是 ES7 提出的实验性功能
开启装饰器
"experimentalDecorators": true,
"emitDecoratorMetadata": true,
类装饰器 ClassDecorator
装饰器作用,在不改变原有代码的前提下,实现在原有逻辑的前后增加功能
const dr: ClassDecorator = (fn) => {
// fn就是Animal的构造函数
console.log(fn)
// 可以给对象挂载属性和方法
fn.prototype.myName = "枫枫"
fn.prototype.getMyName = function () {
console.log(fn.prototype.myName)
}
}
@dr
class Animal {
}
let an = new Animal()
console.log((an as any).myName);
(an as any).getMyName()
原理
const dr: ClassDecorator = (fn) => {
// fn就是Animal的构造函数
console.log(fn)
// 可以给对象挂载属性和方法
fn.prototype.myName = "枫枫"
fn.prototype.getMyName = function () {
console.log(fn.prototype.myName)
}
}
class Animal {
}
dr(Animal)
let an = new Animal()
console.log((an as any).myName);
(an as any).getMyName()
装饰器工厂
使用函数柯里化
const big = (name: string):ClassDecorator=>{
return (fn)=>{
fn.prototype.myName = name
fn.prototype.getMyName = function () {
console.log(fn.prototype.myName)
}
}
}
@big("zhangsan")
class Animal {
}
let an = new Animal()
console.log((an as any).myName);
(an as any).getMyName()
方法装饰器 MethodDecorator
const get: MethodDecorator = (target, propertyKey, descriptor: PropertyDescriptor) => {
descriptor.value("获取的数据")
}
class Animal {
@get
list(data: string) {
console.log(data)
}
}
let an = new Animal()
import axios from "axios";
interface VideoInfo {
id: number
title: string
userName:string
userPic: string
coverUrl: string
playUrl: string
duration: string
}
interface VideoResponse<T> {
code: number
message: string
result: {
total: number
list: T[]
}
}
const get = (url: string): MethodDecorator => {
return (target, propertyKey, descriptor: PropertyDescriptor) => {
axios.get(url).then(res=>{
descriptor.value(res.data)
})
}
}
class Student {
// @get("")
create() {
}
@get("https://api.apiopen.top/api/getHaoKanVideo")
list(data: VideoResponse<VideoInfo>) {
data.result.list.forEach((value, index, array)=>{
console.log(index, value.id, value.title, value.userName)
})
}
}
let s1 = new Student()