2

I've got a question: If I have a constructor in a class:

module.exports = class ClassA{
  constructor(stuffA, stuffB) {
    this.stuffA = stuffA;
    this.stuffB = stuffB;
  }

  NonStaticMethod() {
    console.log(this);
  }

  static StaticMethod(stuffA, stuffB) { 
      const element = new ClassA(stuffA, stuffB);
      console.log(element)
      element.NonStaticMethod();
    });
  }
};

So, the NonStaticMethod prints other information for the object than the StaticMethod. So two questions:

  1. Can I call the constructor from a static method from the same class?

  2. What should be the correct way of calling the non-static method from the static method?

Lenny Will
  • 549
  • 1
  • 4
  • 11
  • 2
    1. Yes, 2. You never call a non-static from a static. You call a method on an instance (non-static) or on a class (static). When you are in a static method, you are not at all in an instance. All is mine on my side, it print two times "ClassA...". What problem are you trying to solve? – Slim May 21 '19 at 13:40
  • 1
    basically, the information stored in the instance are wrong or undefined. So if I would call this.stuffA it would print different information than originally stored in the instance – Lenny Will May 21 '19 at 14:11
  • 1
    I copy paste your code and run it, there is too mush } at the end but there is no issues like you said, see my answer. – Slim May 21 '19 at 14:39

1 Answers1

2

The following code prints "true", so in NonStaticMethod this.stuffA rely correctly on value defined in constructor:

class ClassA{
    constructor(stuffA, stuffB) {
        this.stuffA = stuffA;
        this.stuffB = stuffB;
    }

    NonStaticMethod() {
        console.log(this.stuffA === "a");
    }

    static StaticMethod(stuffA, stuffB) {
        const element = new ClassA(stuffA, stuffB);
        element.NonStaticMethod();
    };
}

ClassA.StaticMethod("a","b")
Slim
  • 1,256
  • 1
  • 13
  • 25
  • 1
    The answer is completely correct due to a mistake, in which I wrongly created the instanced object. Thank you very much – Lenny Will May 21 '19 at 15:52