英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论