typescript的装饰器有点类似Java里的注解,方便便捷对原有函数进行特定功能增强,本文列举了一些小编用到的案例,方便大家参考。
tsconst methodRunTime = () => {
return function(target:any,methodName:string,desc:PropertyDescriptor){
// 保存原来的函数
const originMethod: Function = desc.value;
// 改造函数实现
desc.value = function(...args:any[]){
const start = Date.now();
try {
originMethod.apply(this,args);
} catch (error) {
throw error
} finally {
const end = Date.now()
console.log(`函数 ${methodName} 运行时间: ${end - start} ms`)
}
}
}
}
// 测试案例使用
@methodRunTime()
function fun1(){
// Todo
}
上面的代码稍加改造也可以成为同步异常捕捉器
tsconst methodTryCatch = (errBubble = false) => {
return function(target:any,methodName:string,desc:PropertyDescriptor){
// 保存原来的函数
const originMethod: Function = desc.value;
// 改造函数实现
desc.value = function(...args:any[]){
try {
originMethod.apply(this,args);
} catch (error) {
console.error(`函数 ${methodName} 运行异常 ${error}`)
if(errBubble){
throw error
}
}
}
}
}
// 测试案例使用
@methodTryCatch()
function fun1(){
// Todo
}


本文作者:千寻
本文链接:
版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!