Terminology question: private fields

// A public instance field creates an instance property
class MyClass1 {
  publicInstanceField = 1;
}

// A private instance field creates ???
class MyClass2 {
  #privateInstanceField = 2;
}

If we distinguish:

  • Syntax (how the construct is written in source code)
  • Semantics (what the construct creates)

In the case of public instance fields, syntax and semantics differ. Are they the same in the case of private fields? Or should a new term be introduced for the semantics?

Private fields don’t create properties at all - in terms of the object “having” something, the closest analog to a private field is the spec’s internal slots. The actual semantics are as if the object was the key in a closed-over WeakMap (per field), and the field’s value is the map value.

Generally I’ve just said “has a private field” and nobody’s been confused, so I’m not sure it needs a different term.

1 Like

‘Field’ is not a name of the syntax, it’s a name of the semantic element, albeit one not directly exposed in surface syntax. In the current draft, the grammar production covering both private and public fields is named 𝐹𝑖𝑒𝑙𝑑𝐷𝑒𝑓𝑖𝑛𝑖𝑡𝑖𝑜𝑛 and there is an abstract operation named DefineField, which operates on ClassFieldDefinition abstract records. If ‘field’ referred only to the syntax, the grammar production would be named simply 𝐹𝑖𝑒𝑙𝑑, while the abstract operation would be named something else entirely. There is also the PrivateElement abstract record whose, well, field named [[Kind]] contains a member of an abstract enumeration, of which one possible value is 𝖿𝗂𝖾𝗅𝖽.

1 Like

Generally I’ve just said “has a private field” and nobody’s been confused, so I’m not sure it needs a different term.

Sure, that works. I was mainly asking because a public field does not create any kind of field (it creates a property). So there are different terms for syntax and semantics here.

The actual semantics are as if the object was the key in a closed-over WeakMap (per field), and the field’s value is the map value.

Yes: ECMAScript® 2022 Language Specification

What do you mean by “closed-over”? That keys are not weakly held?

A public field does create a field - its just only observable because it creates a property during construction.

I mean by “closed-over” that it’s like it’s in a closure; the WeakMap itself isn’t visible outside the class (i was describing how you’d implement private field semantics with JavaScript)

1 Like

A public field does create a field - its just only observable because it creates a property during construction.

Right. That’s what I got wrong, terminology-wise (setting up a class vs. instantiating it). Thanks for clarifying!

For explaining how instantiating private fields works, I’d stick with how the spec defines it. I’d also mention using WeakMaps to implement it manually in JavaScript.

1 Like