gpt4 book ai didi

javascript - 如何在 ES6 类中创建 "public static field"?

转载 作者:IT王子 更新时间:2023-10-29 02:47:50 26 4
gpt4 key购买 nike

我正在制作一个 Javascript 类,我希望有一个像 Java 中那样的公共(public)静态字段。这是相关代码:

export default class Agent {
CIRCLE: 1,
SQUARE: 2,
...

这是我得到的错误:

line 2, col 11, Class properties must be methods. Expected '(' but instead saw ':'.

看起来 ES6 模块不允许这样做。有没有办法获得所需的行为,还是我必须编写一个 getter?

最佳答案

您使用访问器和“静态”关键字制作“公共(public)静态字段”:

class Agent {
static get CIRCLE() {
return 1;
}
static get SQUARE() {
return 2;
}
}

Agent.CIRCLE; // 1

查看规范,14.5 — 类定义 — 您会看到一些可疑的相关内容 :)

ClassElement[Yield] :
  MethodDefinition[?Yield]
  static MethodDefinition[?Yield] ;

因此您可以从那里跟随到 14.5.14 — 运行时语义:ClassDefinitionEvaluation — 仔细检查它是否真的像它看起来那样做。具体来说,第20步:

  1. For each ClassElement m in order from methods
    1. If IsStatic of m is false, then
      1. Let status be the result of performing PropertyDefinitionEvaluation for m with arguments proto and false.
    2. Else,
      1. Let status be the result of performing PropertyDefinitionEvaluation for m with arguments F and false.
    3. If status is an abrupt completion, then
      1. Set the running execution context’s LexicalEnvironment to lex.
      2. Return status.

IsStatic 在 14.5.9 中定义较早

ClassElement : static MethodDefinition
Return true.

因此 PropertyMethodDefinition 以“F”(构造函数,函数对象)作为参数调用,这又是 creates an accessor method on that object .

already works至少在 IETP(技术预览)以及 6to5 和 Traceur 编译器中。

关于javascript - 如何在 ES6 类中创建 "public static field"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28445693/

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