JavaScript·100 questions

QUESTION: Что такое getter и setter?

Answer

Getters and setters in JavaScript are special object and class methods that allow you to control access to properties, masking function calls as regular value assignment or reading. A getter is declared using the get keyword before the property name, for example get propertyName() { return this._value; }, and a setter is defined via the set keyword, for example set propertyName(val) { this._value = val; }. The key feature of these constructs is that they are called like regular properties via dot notation, without using parentheses, which makes the interface for working with the object as transparent and natural for the developer as possible.

In practice, getters and setters are indispensable when you need to implement complex validation of incoming data before writing it to a hidden field. For example, an age setter can check if the passed number is positive and throw an error otherwise, protecting the object from an invalid state. Getters, in turn, are great for automatically recalculating computed properties that depend on other parameters on the fly, eliminating the need to manually synchronize data.

In addition to validation and calculations, this mechanism is actively used to log any attempts to read or modify the internal state of an object, which is extremely useful when debugging complex systems. You can easily track at what point in time and what value was assigned to a certain property by adding corresponding console outputs to the setter.

Furthermore, this mechanism is applicable not only in classes, but also in regular object literals, which makes it easy to introduce encapsulation and reactive behavior into a wide variety of data structures in your application without writing redundant boilerplate. This makes the code more reliable, flexible, and resistant to unexpected changes from other program modules.

Was this answer helpful?

More questions in this topic

Related questions from other topics