To declare a public field (that is, a property) on your instance, you can simply declare this within the class definition syntax in line:
class Rectangle {
width = 100;
height = 100;
}
These fields are initialized for each instance and are, therefore, mutable on the instance itself. They're most useful when you need to define some sensible default for a given property. This can then be easily overridden within the constructor:
class Rectangle {
width = 100;
height = 100;
constructor(width, height) {
if (width && !isNaN(width)) {
this.width = width;
}
if (height && !isNaN(height)) {
this.height = height;
}
}
}
You can also define private fields by prefixing their identifier with a # symbol:
class Rectangle {
#width = 100;
#height = 100;
constructor(width, height) {
if (width && !isNaN(width)) {
this.#width = width;
}
if (height && !isNaN(height)) {
this.#height = height;
}
}
}
Private fields are only accessible by the class itself. Sub-classes do not have access:
class Super { #private = 123; }
class Sub { getPrivate() { return this.#private; } }
// !SyntaxError: Undefined private field #private:
// must be declared in an enclosing class
Private fields should be used with extreme caution as they can severely limit the extensibility of your code, hence increasing its rigidity and lack of flexibility. If you use a private field, you should ensure that you have considered the consequences. It may be the case that what you need is, in fact, just a pseudo-private field, prefixed with an underscore (for example, _private) or another obscure piece of punctuation (for example, $_private). Doing this will, by convention, ensure that fellow programmers making use of your interface will (hopefully) understand that they should not make use of the field publicly. If they do so, then the implication is that they may break things. If they wish to extend your class with their own implementation, then they can make use of your private field freely.