How to understand the statement "The only exception is when the two declarations define a getter-setter pair" in the MDN documentation

huangapple go评论62阅读模式
英文:

How to understand the statement "The only exception is when the two declarations define a getter-setter pair" in the MDN documentation

问题

根据MDN(重点在我的):

存在一些额外的语法限制:

  • 在类内声明的所有私有标识符必须是唯一的。命名空间在静态属性和实例属性之间共享。唯一的例外是当两个声明定义了一个 getter-setter 对。
  • 私有标识符不能是 #constructor

如何解释粗体部分的陈述?这是我理解的方式:

class MyClass {
  static #privateProperty = 10; 

  #privateProperty = 20; 

  get #privateProperty() {}
  set #privateProperty(value) {}
}

但是:

Uncaught SyntaxError: Identifier '#privateProperty' has already been declared

您可以帮我解释这个句子,并提供一个使用代码的解释吗?

英文:

Per MDN (emphasis mine):

> There are some additional syntax restrictions:
>
> - All private identifiers declared within a class must be unique. The namespace is shared between static and instance properties. The only
> exception is when the two declarations define a getter-setter pair.

> - The private identifier cannot be #constructor.

How to interpret the bolded statement? This is how I understand it:

class MyClass {
  static #privateProperty = 10; 

  #privateProperty = 20; 

  get #privateProperty() {}
  set #privateProperty(value) {}
}

But:

Uncaught SyntaxError: Identifier '#privateProperty' has already been declared

Can you help me explain this sentence and provide an explanation using code?

答案1

得分: 3

MDN文本表示给定的私有属性名称 #something 只能在类中声明一次,可以作为静态属性或实例属性。当属性打算通过getter和setter函数访问时,名称可以(而且确实必须)出现两次:

get #something() {
  return // whatever
}
set #something(value) {
  whatever(value);
}

就是这样,这是一个相当简单的规则。直接声明getter和setter方法的方式暗示了需要看起来有点像对同一属性进行两次声明。您的代码出现错误,因为您尝试将 #privateProperty 用作静态属性、实例属性以及getter/setter对。选择其中一种方式。

英文:

The MDN text means that a given private property name #something can only be declared once in a class, either as a static property or an instance property. When the property is intended to be accessed via getter and setter functions, the name can (and really must) appear twice:

  get #something() {
    return // whatever
  }
  set #something(value) {
    whatever(value);
  }

That's it; it's a pretty simple rule. The way that getter and setter methods are declared directly implies the need for what looks a little bit like two declarations for the same property. Your code gets errors because you are trying to use #privateProperty as a static property, an instance property, and a getter/setter pair. Pick one.

huangapple
  • 本文由 发表于 2023年6月28日 23:48:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/76574799.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定