MST

星途 面试题库

面试题:TypeScript实现基于装饰器的反射应用

在TypeScript项目里,利用装饰器实现一个反射场景:创建一个`Log`装饰器,当在类的方法上使用这个装饰器时,能通过反射记录方法调用的时间、传入参数等信息并打印出来。
44.1万 热度难度
前端开发TypeScript

知识考点

AI 面试

面试题答案

一键面试
function Log(target: any, propertyKey: string, descriptor: PropertyDescriptor) {
    const originalMethod = descriptor.value;
    descriptor.value = function (...args: any[]) {
        const startTime = new Date();
        console.log(`Method ${propertyKey} called at ${startTime}, with arguments:`, args);
        const result = originalMethod.apply(this, args);
        const endTime = new Date();
        console.log(`Method ${propertyKey} execution time: ${endTime.getTime() - startTime.getTime()} ms`);
        return result;
    };
    return descriptor;
}

class Example {
    @Log
    testMethod(a: number, b: string) {
        console.log(`Inside testMethod with a = ${a} and b = ${b}`);
        return a + b.length;
    }
}

const example = new Example();
example.testMethod(10, 'hello');