javascriptclassaggregationinstantiationgetter

Getter returns undefined in if statement. Seems not working for comparisons


I have a ClockObj which has an AlarmObj in a "HAS A" OOP relationship. Or should I say injected through the constructor.

Inside the AlarmObj I have a isAlarmOn boolean variable. I am returning it using getter.

class AlarmObj {
  isAlarmOn = true
  get getAlarmOnOffStatus() {
    return this.isAlarmOn;
  }
}

class ClockObj {

  constructor(AlarmObjArg) {

    this.AlarmObj = AlarmObjArg

    if (this.AlarmObj.getAlarmOnOffStatus === true) {
      console.log('works')
    }
  }
}

AlarmObj = new AlarmObj();

new ClockObj(AlarmObj)

However it return undefined and when debugging I found that getter is called after the if statement. Is that normal behavior or something is wrong here ?


Solution

  • I created this structure based on your description and it works

    class AlarmObj {
      isAlarmOn = true
      get getAlarmOnOffStatus() { return this.isAlarmOn; }
    }
    
    class ClockObj {
      AlarmObj = new AlarmObj()
      
      constructor() {
        if (this.AlarmObj.getAlarmOnOffStatus === true) {
          console.log('works')
        }
      }
    }
    
    
    new ClockObj()