尝试扩展p5.js库时,super关键字不适用于变量

时间:2019-01-11 13:30:11

标签: angularjs typescript p5.js

我想扩展p5.js库,以便在屏幕上的各个位置显示错误文本。我将在整个应用程序的不同位置使用它,我相信这样做比复制代码更好。

目前,除某些属性外,几乎所有东西都工作正常。例如,如果我访问super.height,我将得到0;而如果我访问this.height,我将得到实际的窗口高度。但是,当访问this.height时,我收到一条错误消息,说height没有在CustomP5中定义,这是正确的,但同时又令人困惑。

import * as p5 from 'p5';

export class CustomP5 extends p5 {
  ... // private fields not related to this issue
  constructor(sketch, htmlElement) {
    super(sketch, htmlElement);

    // Set tooltip error variables
    this.resetTooltipError();
  }

  setSetup(setupFunction) {
    super.setup = () => {
      setupFunction();
      this.setupAdditional();
    }
  }

  setDraw(drawFunction) {
    super.draw = () => {
      drawFunction();
      this.drawAdditional();
    };
  }

  showTooltipError() {
    ...
  }

super.heightsuper.mouseX正常工作的情况下,super.mouseYsuper.drawsuper.mousePressed不起作用是有原因的吗?

PS:我对js和ts很陌生,所以请耐心等待,如果我错了。

1 个答案:

答案 0 :(得分:1)

我不是专家,但听起来super仅适用于函数,而不适用于变量。

您说它适用于super.drawsuper.mousePressed。这些都是功能。您说它不适用于super.heightsuper.mouseXsuper.mouseY。所有这些都是变量。

这与超级的MDN docs相匹配:

  

super 关键字用于访问和调用对象父项上的函数。

class Rectangle {
  constructor(height, width) {
    this.name = 'Rectangle';
    this.height = height;
    this.width = width;
  }
  sayName() {
    console.log('Hi, I am a ', this.name + '.');
  }
  get area() {
    return this.height * this.width;
  }
  set area(value) {
    this.height = this.width = Math.sqrt(value);
  }
}

class Square extends Rectangle {
  constructor(length) {
    this.height; // ReferenceError, super needs to be called first!

    // Here, it calls the parent class' constructor with lengths
    // provided for the Rectangle's width and height
    super(length, length);

    // Note: In derived classes, super() must be called before you
    // can use 'this'. Leaving this out will cause a reference error.
    this.name = 'Square';
  }
}

所以听起来这像预期的那样工作。您可能需要花一些时间来了解JavaScript中继承和super关键字的工作原理。