I was learning about the new class syntax that allows you to put the field initialization code directly in the class body. The wording of the text I’m confused by is as follows. It fully explains the new syntax:
Suppose you’re writing a class like this one, with a constructor that initializes three fields:
class Buffer { constructor() { this.size = 0; this.capacity = 4096; this.buffer = new Uint8Array(this.capacity); } }
With the new instance field syntax, you could instead write:
class Buffer { size = 0; capacity = 4096; buffer = new Uint8Array(this.capacity); }
The field initialization code has moved out of the constructor and now appears directly in the class body. (That code is still run as part of the constructor, of course. If you do not define a constructor, the fields are initialized as part of the implicitly created constructor.) The
this.
prefixes that appeared on the lefthand side of the assignments are gone, but note that you still must usethis.
to refer to these fields, even on the righthand side of the initializer assignments. The advantage of initializing your instance fields in this way is that this syntax allows (but does not require) you to put the initializers up at the top of the class definition, making it clear to readers exactly what fields will hold the state of each instance. You can declare fields without an initializer by just writing the name of the field followed by a semicolon. If you do that,
the initial value of the field will be undefined.
I know this is essentially saying ‘initializing your instance fields this way makes your code more readable,’ however, I don’t see how putting the field initializers themselves at the top of the class definition makes it clearer what field will hold each instance. I’d expect putting the FIELD INITIALIZATION CODE (the initialization assignments), instead of the field initializers, at the top of the class definition to do this; i’m confused as to whether the text was referring to the field initializers themselves or the field initialization code in the phrase “this syntax allows you to put the initializers up at the top of the class definition”
I’ve searched many different sources including Chatgpt, but it keeps changing what it believes ‘initializers’ refers to: sometimes it says it refers to the field initialization code and some other times, it says it refers to the initializers themselves.
10