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

69 Views Asked by At

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 ?

2

There are 2 best solutions below

8
Konrad On BEST ANSWER

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()

0
ILIIA CHTEREV On

My bad. Yes, the getter was returning undefined but that was because the variable itself was undefined. I did not check it because I assumed that if the debugger calls the getter after the comparison this was the problem. It turns however that this is the normal behavior.