简体   繁体   English

具有从子类 JS 调用的方法的类作用域

[英]Class Scope with method called from subclass JS

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?当我控制台日志时,这显示了一个带有所有道具的 Reading 类,它应该 readZoneHeight、wordsPerMinute 等,但是 this.readingZoneHeight 是未定义的,但是在事件侦听器中 this.readingHeight 是正确的值,所以不确定这里发生了什么?

Anyone Help?任何人帮助?

That happens because you are calling the Reading 's processEvent method from the constructor of the ElementEvent .那是因为你所呼叫的ReadingprocessEvent从的构造方法ElementEvent So this is actually called as part of the super(event) call in the constructor of the Reading class.所以这实际上是在Reading类的构造函数中作为super(event)调用的一部分调用的。

And since the super(event) happens before you actually assign anything to the this.readingZoneHeight it is undefined at the time you log it.并且由于super(event)在您实际将任何内容分配给this.readingZoneHeight之前发生,因此在您记录它时它是undefined的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM