当前位置: 首页 > news >正文

学习ts(十)装饰器

定义

装饰器是一种特殊类型的声明,它能够被附加到类声明,方法,访问符,属性或参数上,是一种在不改变原类和使用继承的情况下,动态的扩展对象功能。
装饰器使用@expression形式,其中expression必须评估为一个函数,该函数将在运行时调用,并带有有关装饰声明的信息。
前置操作

// tsconfig.json
{"compilerOptions": {"target": "ES5","experimentalDecorators": true}
}

使用

类装饰

类装饰器会把Class A的构造函数传入你的watcher函数当做第一个参数

const watcher: ClassDecorator = (target) => {target.prototype.age = 18target.prototype.getName = ():string=>{return 'hello'}
}
@watcher
class A {constructor() {}
}
const a = new A()
console.log((a as any).age);  // 18
console.log((a as any).getName());  //hello

装饰器工厂

如果想要传递参数,使装饰器变成类似工厂函数,只需要在装饰器函数内部再返回一个函数即可。

const watcher = (name: string): ClassDecorator => {return (target) => {target.prototype.age = 18target.prototype.getName = (): string => {return name}}}
@watcher('hello data')
class A {constructor() {}
}
const a = new A()
console.log((a as any).age); // 18
console.log((a as any).getName()); // hello data

装饰器组合

可以给一个类使用多个装饰器

const watcher = (name: string): ClassDecorator => {return (target) => {target.prototype.age = 18target.prototype.getName = (): string => {return name}}}const addAge = (age:number):ClassDecorator => {return (target) =>{target.prototype.addAge = (): number => {return age+1}}
}@watcher('hello data')  @addAge(20)
class A {constructor() {}
}
const a = new A()
console.log((a as any).age);
console.log((a as any).getName());
console.log((a as any).addAge());

方法/属性装饰器

装饰器参数为:

  • target:对象的原型:对于静态成员来说是类的构造函数,对于实例成员是类的原型对象
  • propertyKey:方法的名称
  • descriptor:方法的属性描述符
    这三个属性实际就是Object.defineProperty的三个参数,如果是类的属性,则没有传递第三个参数
const met: MethodDecorator = (...args) => {console.log(args)
}class A {constructor() {}@metgetName(): string {return 'hello'}
}const xx = new A()

在这里插入图片描述

// 声明装饰器修饰方法/属性
function method(target: any, propertyKey: string, descriptor: PropertyDescriptor) {descriptor.writable = false;
};function property(target: any, propertyKey: string) {// 修改属性target[propertyKey] = '11223'
}class Person {@propertyname: string;constructor() {}@methodsay() {return 'instance method';}
}const xmz = new Person();// 修改实例方法say
xmz.say = () => {return '5566'   //由于 descriptor.writable = false; 所以此处修改不生效
}
console.log(xmz.name)
console.log(xmz.say())  // nstance method

参数装饰

装饰器参数为:

  • target:当前对象的原型
  • propertyKey:参数的名称
  • index:参数数组中的位置
const init: ParameterDecorator = (...args)=>{console.log(args)
}
class A {constructor() {}getName(@init name: string = 'hello') {console.log(name) // [ {}, 'getName', 0 ]}
}

元数据

import data from './data.json'
import 'reflect-metadata'const Base = (base: string) => {return (target) => {target.prototype.base = base}
}const GetData = (url: string) => {console.log('getData run')const fn: MethodDecorator = (target: any, key, descriptor: PropertyDescriptor) => {const prop = Reflect.getMetadata('key', target)console.log(prop, 'prop')descriptor.value(prop ? data[prop] : data)}return fn;
}const Result = () => {console.log('result run')const fn: ParameterDecorator = (target: any, key, index) => {Reflect.defineMetadata('key', 'data', target)}return fn
}@Base('/api')
class Http {fileName: stringconstructor(name) {this.fileName = name}@GetData('json')getList(@Result() data: any) {console.log(data)}
}
const http = new Http('orange')
http://www.lryc.cn/news/143349.html

相关文章:

  • 如何在 Opera 中启用DNS over HTTPS
  • STM32 F103C8T6学习笔记13:IIC通信—AHT10温湿度传感器模块
  • QT基础使用:组件和代码关联(信号和槽)
  • TCP最大连接数问题总结
  • 【Docker】云原生利用Docker确保环境安全、部署的安全性、安全问题的主要表现和新兴技术产生
  • explain各个字段代表的意思
  • 【已解决】Windows10 pip安装报错:UnicodeDecodeError: ‘gbk‘ codec can‘t decode byte 0x98
  • goland 中的调试器 -- Evaluate
  • 你知道公司内部维基到底有哪些功能吗
  • netdata监控服务器主机(包括Docker容器)
  • Mybatis学习|第一个Mybatis程序
  • 计算机网络MTU和MSS的区别
  • redis学习笔记 - 进阶部分
  • SE5 - BM1684 人工智能边缘开发板入门指南 -- 模型转换、交叉编译、yolov5、目标追踪
  • 基于Java+SpringBoot+vue前后端分离英语知识应用网站设计实现
  • vue使用vue-router报错
  • 编写Dockerfile制作Web应用系统nginx镜像,生成镜像nginx:v1.1,并推送其到私有仓库。
  • js 类、原型及class
  • day-30 代码随想录算法训练营 回溯part06
  • txt、pcd、las、ply 格式点云基本的读写和显示 (附 python c++ 代码)
  • k8s节点pod驱逐、污点标记
  • 【项目 计网6】 4.17 TCP三次握手 4.18滑动窗口 4.19TCP四次挥手
  • 茶叶小笔记
  • 安全开发-JS应用NodeJS指南原型链污染Express框架功能实现审计WebPack打包器第三方库JQuery安装使用安全检测
  • Android JNI系列详解之CMake编译工具的使用
  • springboot中关于继承WebMvcConfigurationSupport后自定义的全局Jackson失效解决方法,localdate返回数组问题
  • LeetCode 面试题 02.03. 删除中间节点
  • Redis知识点总结
  • (四)k8s实战-服务发现
  • AxureRP制作静态站点发布互联网,内网穿透实现公网访问