主要介绍代理模式的实现方案和我在开发中的一点应用(真的只有一点)
node中代理模式的实现方案主要有三种:对象组合,对象增强和ES2015中的Proxy对象,主要使用最后一种方式进行应用
主要利用Proxy代理封装了一个计算函数耗时的代理
module.exports.Consuming = function (fun,funName) {
return new Proxy(fun, {
async apply(target, thisArg, args) {
// thisArg :The this argument for the call. 就是调用的this
// console.log(fun.toString());
// 拿不到函数名,因为本身就是匿名函数,考虑获取实际参数名代替函数名
const start = new Date().getTime();
const result = await target(...args);
const end = new Date().getTime();
console.log(`${new Date().format('yyyy-MM-dd hh:mm:ss')} 函数[${funName}]耗时:${end - start}ms`);
return result;
}
})
}
使用方式:
const proxy= await Consuming(yourFunction,functionName);
const result = await proxy(params); // 原来的参数
这样只需要将这两行代码替换掉原来的调用,就不用自己写console.log(new Date …!@#!@$#@%了
缺点如果调用比较多,会分不清是哪个调用打出来的耗时,需要在进行代理的时候手动传入函数名