首页 > 解决方案 > Babel:TypeError:无法将类作为函数调用

问题描述

我创建了一个装饰器功能

export function classLogger(target: any) {
    const classFunctions = Object.getOwnPropertyNames(target.prototype).filter(item => typeof target.prototype[item] === 'function')
    for (const propertyName of classFunctions) {
        const descriptor = Object.getOwnPropertyDescriptor(target.prototype, propertyName);
        const originalMethod = descriptor.value;
            if (descriptor.value.constructor.name === 'Function') {
                descriptor.value = function (...args: any[]) {
                    logArguments(propertyName, args);
                    return originalMethod.apply(this, args);
                };
            } else if (descriptor.value.constructor.name === 'AsyncFunction') {
                descriptor.value = async function (...args: any[]) {
                    logArguments(propertyName, args);
                    return await originalMethod.apply(this, args);
                };
            }
            Object.defineProperty(target.prototype, propertyName, descriptor); 
    }
}

我在我的 Javascript 类中使用这个函数

@classLogger
class A extends B {
    someMethod(){
    
    }
}

当我尝试使用它时

new A().someMethod()

我一直收到这个错误。 TypeError: Cannot call a class as a function 我确信这是由于某些 babel 转换。因为我已经为上面的装饰器编写了测试用例,它看起来工作正常。但是当我在 Babel 7 的节点项目中使用它时。它给了我运行时错误。我的节点版本是 14.16.0。我至少想知道这个问题的原因。

标签: javascriptnode.jsclassbabeljsdecorator

解决方案


推荐阅读