在 Javascript 中,是否可以在 运行 时间访问字段的注释数据?
In Javascript, is it possible to access a field's annotated data at run time?
给定示例 JavaScript 代码:
function foo = key => target => {
target.key = key;
return target;
}
class Bob {
@foo('hello')
a = 'world';
}
const bob = new Bob();
有没有办法在 运行 时从注释字段访问 key
的值?像 :
getAnnotationTarget(bob, 'a').key; // "hello"
这个问题的重点是允许 class 字段注释,并从注释中检索与该字段关联的数据。该字段的值本身不应受到影响,即 bob.a = "blah";
不应影响与该字段关联的注释值。
我天真的想法是从注解中扩展字段的原型,但是执行注解时似乎不可用。
谢谢。
您可以将(隐藏的)地图添加到 class,然后查找:
const hidden = Symbol();
decorator @foo(value) {
@register((target, prop) => {
if(!target[hidden]) target[hidden] = new Map();
target[hidden].set(prop, value);
}
}
const getAnnotationTarget = (instance, key) =>
instance.constructor[hidden].get(key);
或者使用 babel 提案语法装饰器看起来像:
const foo = (value) => (target, prop) => {
target = target.constructor;
if(!target[hidden]) target[hidden] = new Map();
target[hidden].set(prop, value);
};
给定示例 JavaScript 代码:
function foo = key => target => {
target.key = key;
return target;
}
class Bob {
@foo('hello')
a = 'world';
}
const bob = new Bob();
有没有办法在 运行 时从注释字段访问 key
的值?像 :
getAnnotationTarget(bob, 'a').key; // "hello"
这个问题的重点是允许 class 字段注释,并从注释中检索与该字段关联的数据。该字段的值本身不应受到影响,即 bob.a = "blah";
不应影响与该字段关联的注释值。
我天真的想法是从注解中扩展字段的原型,但是执行注解时似乎不可用。
谢谢。
您可以将(隐藏的)地图添加到 class,然后查找:
const hidden = Symbol();
decorator @foo(value) {
@register((target, prop) => {
if(!target[hidden]) target[hidden] = new Map();
target[hidden].set(prop, value);
}
}
const getAnnotationTarget = (instance, key) =>
instance.constructor[hidden].get(key);
或者使用 babel 提案语法装饰器看起来像:
const foo = (value) => (target, prop) => {
target = target.constructor;
if(!target[hidden]) target[hidden] = new Map();
target[hidden].set(prop, value);
};