在Javascript中,是否可以在运行时访问字段的注释数据?

时间:2019-07-15 20:50:24

标签: javascript annotations babel

给出示例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"

这个问题的重点是允许类字段注释,并从注释中检索与该字段关联的数据。字段的值本身不应该受到影响,即bob.a = "blah";不应影响与该字段关联的注释值。

我幼稚的想法是从注释中扩展该领域的原型,但是执行注释时似乎不可用。

谢谢。

1 个答案:

答案 0 :(得分:1)

您可以在课程中添加一个(隐藏的)地图,然后进行查找:

 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);

 };