1

I have a subclass that does some validation stuff that calls a method in the parent class that extends it, this is working in all places except when I need to access the local scope in the parent class, see example below

subclass

export default class ElementEvent extends Core {
  constructor(events){
    super(events);

    this.validation = this.validateEvent();
    this.element = this.getElement();
    this.triggered = false;
    this.player = false;
    this.waitForElementDelay = 3000;

    if (this.validation){
      if (this.element){
        this.processEvent();
      } else {
        this.waitForElement();
      }
    }

waitForElement(){
    const interval = setInterval(()=>{
      const el = this.getElement();
      if (el){
         this.element = el;
        this.processEvent();
        clearInterval(interval);
      }
    }, this.waitForElementDelay)
  }
  }

parent

export default class Reading extends ElementEvent {
  constructor(event) {
    super(event);
    this.readingZoneHeight = 50; 
    this.wordsPerMinute = 300;
    this.timer = 0;
  }

  processEvent() {
    //this.elementEntryPoint = this.getElementEntryPoint();
    //this.elementExitPoint = this.getElementExitPoint();

    console.log(this);
    console.log(this.readingZoneHeight);
    window.addEventListener('scroll', () => {
      console.log('Inside Event Listener ' + this.readingZoneHeight);
      //this.handleWindowScroll();
    });
  }
}

When I console log this is shows a Reading class with all the props it should readingZoneHeight, wordsPerMinute etc but this.readingZoneHeight is undefined, however inside the event listener this.readingHeight is the correct value so not sure whats happening here?

Anyone Help?

1
  • you should've point out where it's undefined. It's like finding needle in haystack Commented Feb 6, 2018 at 9:09

1 Answer 1

1

That happens because you are calling the Reading's processEvent method from the constructor of the ElementEvent. So this is actually called as part of the super(event) call in the constructor of the Reading class.

And since the super(event) happens before you actually assign anything to the this.readingZoneHeight it is undefined at the time you log it.

Sign up to request clarification or add additional context in comments.

1 Comment

Ahh yes that makes sense, i've moved the props down from the constructor to the processEvent method and it works perfectly :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.