1

I want to extend the p5.js library in order to have error text on various locations on the screen. I will be using it in different places throughout my app and I believe it's better to do this than duplicating the code.

For now, almost everything is working fine, except some properties. For example, if I access super.height I'll get 0, while if I access this.height I'll get the actual window height. But, when accessing this.height I get an error saying that height isn't defined in CustomP5, which is right, but at the same time confusing.

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() {
    ...
  }

Is there a reason why super.height, super.mouseX, and super.mouseY don't work, while super.draw or super.mousePressed are working correctly?

PS: I'm quite new to js and ts, so be patient if I'm wrong, please.

Kevin Workman
  • 41,537
  • 9
  • 68
  • 107
Dorinel Panaite
  • 492
  • 1
  • 6
  • 15

1 Answers1

1

I'm not an expert, but it sounds like super only works with functions, not variables.

You say it works with super.draw and super.mousePressed. These are both functions. You say it does not work with super.height, super.mouseX, or super.mouseY. All of these are variables.

This matches the MDN docs for super:

The super keyword is used to access and call functions on an object's parent.

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';
  }
}

So it sounds like this is working as intended. You might want to take some time to read up on how inheritance and the super keyword work in JavaScript.

Kevin Workman
  • 41,537
  • 9
  • 68
  • 107