繁体   English   中英

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

[英]Class Scope with method called from subclass JS

我有一个子类,它执行一些验证工作,调用父类中扩展它的方法,这在所有地方都有效,除非我需要访问父类中的本地范围,请参见下面的示例

子类

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

父母

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

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

任何人帮助?

那是因为你所呼叫的ReadingprocessEvent从的构造方法ElementEvent 所以这实际上是在Reading类的构造函数中作为super(event)调用的一部分调用的。

并且由于super(event)在您实际将任何内容分配给this.readingZoneHeight之前发生,因此在您记录它时它是undefined的。

暂无
暂无

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

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