TIL - getter & setter


☄️ Getter


  • Getters can perform an action on the data when getting a property.

  • Getters can return different values using conditionals.

  • In a getter, we can access the properties of the calling object using this

  • The functionality of our code is easier for other developers to understand.

  • Literally, When you get something, it will return something.

  • When using getter (and setter) methods is that properties cannot share the same name as the getter/setter function. Otherwise, It will cause the call stack error.
    👉 したがって、通常、前の「」を使用すると、ゲストとゲストに書き込まれる変数名が異なります.
  • const person = {
      _firstName: 'John',
      _lastName: 'Doe',
      get fullName() {
        if (this._firstName && this._lastName){
          return `${this._firstName} ${this._lastName}`;
        } else {
          return 'Missing a first name or a last name.';
        }
      }
    }
     // To call the getter method: 
    person.fullName; // 'John Doe'

    ☄️ Setter

  • checking input, performing actions on properties, and displaying a clear intention for how the object is supposed to be used.
  • const robot = {
      _model: '1E78V2',
      _energyLevel: 100,
      _numOfSensors: 15,
      get numOfSensors(){
        if(typeof this._numOfSensors === 'number'){
          return this._numOfSensors;
        } else {
          return 'Sensors are currently down.'
        }
      },
      set numOfSensors(num) {
    if(typeof num === "number" && num >= 0) {
      return this._numOfSensors = num
    } else {
    console.log( 'Pass in a number that is greater than or equal to 0')
    }
      }
    }; 
    robot.numOfSensors = 100;
    console.log(robot.numOfSensors)

    ☄️ in a nutshell


    getter


    値を返します.
    ゲストを定義すると、上記のpropertyデータを受信するのではなく、ゲストが呼び出されます.

    setter


    値を設定します.
    新しい受信済み価値設定値を使用します.セッションを定義すると、メモリ値を更新するのではなく、セッションが呼び出されます.
    ユーザーが設定できない値が書き込まれないように、セッションを使用して設定します.
    参考資料
    codecademy https://www.codecademy.com/courses/introduction-to-javascript/lessons/advanced-objects/exercises/setters
    DREAM符号化https://www.youtube.com/watch?v=_DLhUBWsRtw
    9:30 ~