MST
星途 面试题库

面试题:TypeScript 装饰器在 AOP 编程中的基础应用

请用 TypeScript 装饰器实现一个简单的 AOP 切面,在一个函数执行前打印 'Before function execution',执行后打印 'After function execution'。
38.0万 热度难度
前端开发TypeScript

知识考点

AI 面试

面试题答案

一键面试
// 定义装饰器
function aopAspect(target: any, propertyKey: string, descriptor: PropertyDescriptor) {
    const originalMethod = descriptor.value;
    descriptor.value = function(...args: any[]) {
        console.log('Before function execution');
        const result = originalMethod.apply(this, args);
        console.log('After function execution');
        return result;
    };
    return descriptor;
}

class ExampleClass {
    @aopAspect
    exampleFunction() {
        console.log('Inside the function');
    }
}

const example = new ExampleClass();
example.exampleFunction();