JavaScript Style Guide - Accessors

Jang Seok Woo·2022년 8월 12일
0

실무

목록 보기
121/136

24. 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').

// bad
class Dragon {
  get age() {
    // ...
  }

  set age(value) {
    // ...
  }
}

// good
class Dragon {
  getAge() {
    // ...
  }

  setAge(value) {
    // ...
  }
}

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

// bad
if (!dragon.age()) {
  return false;
}

// good
if (!dragon.hasAge()) {
  return false;
}

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

class Jedi {
  constructor(options = {}) {
    const lightsaber = options.lightsaber || 'blue';
    this.set('lightsaber', lightsaber);
  }

  set(key, val) {
    this[key] = val;
  }

  get(key) {
    return this[key];
  }
}

출처 : https://github.com/airbnb/javascript

profile
https://github.com/jsw4215

0개의 댓글