Public and private fields

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;
}
}
}
Traditionally, JavaScript had no concept of private fields, so programmers opted instead to prefix properties intended as private with one or more underscores (for example, __somePropertyName). This was understood as a social contract where other programmers would not mess with these properties (knowing that doing so might break things in unexpected ways).

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.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.143.5.15