0

this.#staticAntall" doesn't refer to the class, and therefore returns an error.

Is this referring to the constructor in that case?

And is there a reference I can use to refer to the class(since I am going to write multiple classes it would be nice to not have to have class referrences from names.

Allergy.js:32 Uncaught TypeError: Cannot read private member #staticAntall from an object whose class did not declare it

I wish to just write this.#staticAntall ++;

or return this.#staticAntall;

It seems like I am having problems with the way I use static too. Here I want to count the number of GlutenIntoleranse-classes So that I can use that value afterwards.

What does the # infront of static stand for?

at new GlutenIntoleranse (Allergy.js:32)
at <anonymous>:1:10

class Allergy {
  constructor(name, tag, description, advice) {
    this.name = name || "Ingen navn";
    this.tag = tag || "Ingen forkortelse";
    this.description = description || "Ingen beskrivelse";
    this.advice = advice || "Ingen råd";
  }
  //methods...
}

class GlutenIntoleranse extends Allergy {
  static #staticAntall = 0;
  constructor() {
    super("GlutenIntoleranse", "GLT-I", "Gluten intoleranse", "Skal ikke serveres gluten");
    increaseAntall();
    //GlutenIntoleranse.#staticAntall++;
    this.#staticAntall += 1;
    console.log(GlutenIntoleranse.#staticAntall);
  }

  increaseAntall() {
    GlutenIntoleranse.#staticAntall++;
  }
}
Barmar
  • 741,623
  • 53
  • 500
  • 612
Thinked
  • 49
  • 1
  • 1
  • 7

1 Answers1

0

this refers to a specific instance of your class. If you want to call static fields, you should call it with the class name, instead of this. In your case: GlutenIntoleranse.#staticAntall++.

Regarding the other question, "What does the # infront of static stand for?". That is a experimental feature, with the goal to define the field as private (Reference)

Edit: Edited the last sentence according to Bergi comment

Jose Nuno
  • 598
  • 3
  • 13
  • 1
    "*That is a feature from ES2019*" - no, definitely not. It's still an experimental proposal an might find its way into ES2021 or even later. – Bergi Jul 31 '20 at 00:45
  • I stand corrected. I misread the documentation. I edited the answer. – Jose Nuno Jul 31 '20 at 00:48
  • 1
    (I've got to admit that I just edited MDN, it was stated there wrongly as well) – Bergi Jul 31 '20 at 00:49