skip to Main Content

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

Answers


  1. Chosen as BEST ANSWER

    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.


  2. 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()
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search