NodeJS 中允许使用装饰器吗?

dav*_*raj 5 node.js javascript-decorators

我正在尝试使用终端在 NodeJS 中运行以下代码

function addStringToName(target, name, descriptor) {
    const fn = descriptor.value;
    descriptor.value = wrestler => {
        fn.call(target, wrestler + ' is a wrestler');
    };
}

class Wrestler {
    @addStringToName
    setName(name) {
        this.name = name;
    }
    sayName() {
        console.log(this.name);
    }
}

const w = new Wrestler();
w.setName('Macho Man');
w.sayName();
Run Code Online (Sandbox Code Playgroud)

出现以下错误

错误

NodeJS 中可以使用装饰器吗?如果可以的话,编写的代码有什么问题吗?

Ego*_*dev 3

很不幸的是,不行。您必须使用 TypeScript 才能启用装饰器。而且,即使 TypeScript 本身也不支持它。你必须target: "ES5"至少有 和"experimentalDecorators": true

您可以在这里找到有关装饰器和 TypeScript 的更多信息:https ://www.typescriptlang.org/docs/handbook/decorators.html

  • 是的,我明白。但它们在 **JS * 和 * TS** 中都是实验性的/提案,而你的答案错误地指出 *“你必须使用 TypeScript”*。 (2认同)