如何通过Babel在类实例上使用JavaScript装饰器?

塔马斯

给定以下.babelrc配置:

{
  "plugins": [
    ["@babel/plugin-proposal-decorators", {
      "legacy": false,
      "decoratorsBeforeExport": false
    }]
  ]
}

我不能让类装饰器起作用:

@annotation
class MyClass { }

function annotation(target) {
   target.annotated = true;
}

const c = new MyClass();
console.log(c);

同样,console.log(target)产生以下内容:

Object [Descriptor] { kind: 'class', elements: [] }

对于该console.log(c)语句,我希望看到添加了带注释的属性,但是得到的只是MyClass {}

一些其他说明-我知道该legacy: true标志,但是我希望使用现在的规范,而不会遗留下来。我做了一些额外的研究,我想我在这里的正确路径上,这是更新的代码:

@annotation
class MyClass { }

function annotation(descriptor) {
  const {
    kind,
    elements
  } = descriptor;

  const newElements = elements.concat([{
    kind: 'field',
    placement: 'own',
    descriptor: {
      annotated: true
    }
  }]);
  return {
    kind,
    elements: newElements
  }
}

const c = new MyClass();
console.log(c);

以上仍然无法正常工作,但至少我不再遇到奇怪的错误了:)

如果有兴趣,请阅读已接受答案的评论,以查看一些可能的解决方案。

**更新**我实际上设法弄清楚了-使用以下legacy: false选项:

@annotation
class MyClass { }

function annotation(descriptor) {
  const {
    kind,
    elements
  } = descriptor;

  const newElements = elements.concat([{
    kind: 'field',
    placement: 'own',
    key: 'annotated',
    initializer: () => true,
    descriptor: {
      configurable: true,
      writable: true,
      enumerable: true
    }
  }]);
  return {
    kind,
    elements: newElements
  }
}

const c = new MyClass();
console.log(c); // MyClass { annotated: true }
杰普拉特

返回一个新类,该类在构造函数中设置属性。

@annotation
class MyClass { }

function annotation(target) {
  return class extends target {
    constructor(...args) {
      super(...args);
      this.annotated = true;
    }
  }
}

const c = new MyClass();
console.log(c);

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章