gpt4 book ai didi

javascript - 在 Node.js 中使用装饰器

转载 作者:太空宇宙 更新时间:2023-11-04 03:00:13 25 4
gpt4 key购买 nike

我是 Node.js 的新开发者(来自 Python),我很惊讶地发现 Javascript 中没有装饰器。不过,我想使用它,因为它大大简化了代码。

经过一番研究,我在第 2 阶段找到了一个 ES6 规范( https://github.com/tc39/proposal-decorators ),但 Node.js 显然不支持它。我还在 TypeScript 中找到了这个,但它们的功能是有限的(仅在类中)。

所以我的问题是:有没有一种方法可以在 Node.js 中使用类似于 Python 的装饰器,如果没有,可以使用哪些功能来替代?

预先感谢您的回答!

最佳答案

根据Wikipedia python 中的装饰器只是函数调用的语法糖,它采用原始类/函数并将返回值存储在包含该类的变量下。因此等效的 js 是:

  const Decorated = decorator(class ToBeDecorated {
/*...*/
});

const decoratedFunction = decorateFunction(function decorated() {
/*...*/
});

// Some sample decorator implementations:
const decorator = Parent => class WithDuck extends Parent {
quack() { }
};

const decorateFunction = fn => (...args) => {
console.log(`${fn.name} called with`, ...args);
return fn(...args);
};

关于javascript - 在 Node.js 中使用装饰器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59228905/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com