【发布时间】:2023-04-09 11:51:01
【问题描述】:
很好奇我们如何在运行时调用属性装饰器。例如,如果我们运行以下代码:
function PropertyDecorator(
target: Object, // The prototype of the class
propertyKey: string | symbol // The name of the property
) {
console.log("PropertyDecorator called on: ", target, propertyKey);
}
class PDE {
@PropertyDecorator
name: string;
}
它将记录PropertyDecorator called on: PDE {} name,因此在类加载时会调用装饰器。假设我们想在 PDE 的实例上再次调用它,如下所示:
const newPDE = PDE();
callDecoratorsOnProperties(newPDE);
这是怎么做到的?
【问题讨论】:
-
您无法重新运行装饰器,但根据您要执行的操作,有不同的解决方案可以运行代码
-
据我了解,装饰器在创建类时被应用为对类的修改。如果您查看装饰器的转译方式,它似乎不会在类创建之外持续存在。 babeljs.io/repl(通过插件部分打开旧版装饰器插件以查看它的实际效果)
-
浏览github.com/typestack/class-validator 的代码库...但它有点“参与”所以我试图了解他们是如何使用
validate(instance)调用装饰器...
标签: javascript typescript annotations decorator