MST

星途 面试题库

面试题:TypeScript中装饰器模式的基本实现

请使用TypeScript实现一个简单的装饰器模式,假设我们有一个类`User`,有一个方法`getName`,现在需要用装饰器给`getName`方法添加日志功能,在调用该方法前后打印日志信息。
37.5万 热度难度
前端开发TypeScript

知识考点

AI 面试

面试题答案

一键面试
function log(target: any, propertyKey: string, descriptor: PropertyDescriptor) {
    const originalMethod = descriptor.value;
    descriptor.value = function(...args: any[]) {
        console.log(`调用 ${propertyKey} 方法前`);
        const result = originalMethod.apply(this, args);
        console.log(`调用 ${propertyKey} 方法后`);
        return result;
    };
    return descriptor;
}

class User {
    private name: string;
    constructor(name: string) {
        this.name = name;
    }

    @log
    getName() {
        return this.name;
    }
}

const user = new User('John');
console.log(user.getName());