Working on an ultra-modern JavaScript codebase? You’ve likely seen this:
class Cat {
goes = "purr";
}
That goes
there? It’s called a public instance field or a public field declaration.
Fancy words for essentially the same thing as instance variables.
It serves two purposes:
- make the code read better, and,
- ensure a variable always exists.
That’s it.
The MDN documentation goes so:
By declaring fields up-front, class definitions become more self-documenting, and the fields are always present.
MDN Web Docs
Don’t get hung up on these things like I do. There will be a few gotchas as you use them. But you’ll figure it out.
There’s more: privacy.
It also opens up a neat syntax for private instance variables:
class Cat {
goes = "purr";
#hideaway = "WON'T TELL YOU, HUMAN!"
}
All cats purr and have a secret hideaway. Makes sense.
Experimental.
Of course, this is not officially a part of ECMAScript yet, but we like to transpile things down everywhere we can in our ultra-modern programming society. Use babel
and friends — you’ll be fine.
It’s a Stage 3 feature (‘Candidate’), one step away from ‘Finished’. You should be fine using it today.