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?

3
  • 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? Commented May 21, 2019 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 Commented May 21, 2019 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. Commented May 21, 2019 at 14:39

1 Answer 1

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")
Sign up to request clarification or add additional context in comments.

1 Comment

The answer is completely correct due to a mistake, in which I wrongly created the instanced object. Thank you very much

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.