MST

星途 面试题库

面试题:TypeScript方法装饰器与类继承

在TypeScript中,当一个带有方法装饰器的类被继承时,子类对该方法的调用,装饰器会如何表现?请通过代码示例进行说明,并解释原因。
35.1万 热度难度
前端开发TypeScript

知识考点

AI 面试

面试题答案

一键面试

代码示例

function methodDecorator(target: any, propertyKey: string, descriptor: PropertyDescriptor) {
    const originalMethod = descriptor.value;
    descriptor.value = function(...args: any[]) {
        console.log('Before method execution');
        const result = originalMethod.apply(this, args);
        console.log('After method execution');
        return result;
    };
    return descriptor;
}

class ParentClass {
    @methodDecorator
    someMethod() {
        console.log('Parent method');
    }
}

class ChildClass extends ParentClass {
    someMethod() {
        super.someMethod();
        console.log('Child method');
    }
}

const child = new ChildClass();
child.someMethod();

解释

  1. 装饰器定义methodDecorator 是一个方法装饰器,它在目标方法执行前后添加了日志输出。
  2. 父类ParentClass 中的 someMethodmethodDecorator 装饰。当调用 ParentClasssomeMethod 时,会先输出 Before method execution,然后执行原方法,最后输出 After method execution
  3. 子类ChildClass 继承自 ParentClass 并覆盖了 someMethod。在 ChildClasssomeMethod 中,通过 super.someMethod() 调用父类被装饰的方法。所以,在执行 super.someMethod() 时,依然会遵循父类中装饰器的逻辑,即先输出 Before method execution,执行父类原方法,再输出 After method execution。之后,再输出 Child method
  4. 结论:当带有方法装饰器的类被继承时,子类调用父类被装饰的方法(通过 super),装饰器的逻辑依然会生效,因为装饰器逻辑是在定义父类方法时就已经应用并修改了方法的执行逻辑。