要创建一个方法装饰器,在方法执行前后打印字符串“start”和“end”,你可以按照以下步骤来实现。这个装饰器将包装原始方法,并在执行前后添加日志。
步骤
-
定义装饰器函数:装饰器函数通常接受三个参数:目标对象、方法名称和属性描述符。
-
在装饰器中包装原始方法:拦截方法调用,在调用前和调用后添加日志打印。
-
返回新的属性描述符:将修改后的函数设置为属性描述符的值。
示例代码
function LogExecution(
target: Object,
propertyName: string | symbol,
descriptor: PropertyDescriptor
) {
const originalMethod = descriptor.value; // 保存对原始方法的引用
descriptor.value = function (...args: any[]) {
console.log('start'); // 方法开始前打印
// 调用原始方法
const result = originalMethod.apply(this, args);
console.log('end'); // 方法结束后打印
return result; // 返回原始方法的结果
};
return descriptor; // 返回修改后的描述符
}
class Example {
@LogExecution
myMethod() {
console.log('Executing myMethod');
}
}
const exampleInstance = new Example();
exampleInstance.myMethod();
解释
-
LogExecution装饰器:这是一个方法装饰器,它用来拦截对目标方法的调用。 -
target:方法所属的类的原型对象。 -
propertyName:方法的名称。 -
descriptor:属性描述符,包含方法的详细信息。 -
包装原始方法:
-
originalMethod.apply(this, args):利用apply方法调用原始函数,并传递当前的上下文(this)和参数(args)。 -
打印日志:
-
在调用原始方法之前打印
"start"。 -
在调用原始方法之后打印
"end"。
通过这种方式,你可以在方法执行的生命周期中插入自定义逻辑,比如日志记录,这对调试和监控非常有用。需要注意的是,装饰器的返回值是一个新的属性描述符,它替换了原始的方法实现。