Accessors

  • 24.1 Accessor functions for properties are not required.

  • 24.2 Do not use JavaScript getters/setters as they cause unexpected side effects and are harder to test, maintain, and reason about. Instead, if you do make accessor functions, use getVal() and setVal('hello').

    1. // bad
    2. class Dragon {
    3. get age() {
    4. // ...
    5. }
    6. set age(value) {
    7. // ...
    8. }
    9. }
    10. // good
    11. class Dragon {
    12. getAge() {
    13. // ...
    14. }
    15. setAge(value) {
    16. // ...
    17. }
    18. }

  • 24.3 If the property/method is a boolean, use isVal() or hasVal().

    1. // bad
    2. if (!dragon.age()) {
    3. return false;
    4. }
    5. // good
    6. if (!dragon.hasAge()) {
    7. return false;
    8. }

  • 24.4 It’s okay to create get() and set() functions, but be consistent.

    1. class Jedi {
    2. constructor(options = {}) {
    3. const lightsaber = options.lightsaber || 'blue';
    4. this.set('lightsaber', lightsaber);
    5. }
    6. set(key, val) {
    7. this[key] = val;
    8. }
    9. get(key) {
    10. return this[key];
    11. }
    12. }