0

The first of the below code examples is what I am doing today, where I initialise the global variables in the constructor.

But would there be any harm in moving the global variables out in the class, as seen in the second example?

class Alert {
  constructor(alert) {
    this.load = JSON.parse('{}');
    this.alert = alert;
    this.#coolDownTime = 0;
  };

  #coolDownTime;
}

vs just doing

class Alert {
  constructor(alert) {
    this.alert = alert;
  };

  #coolDownTime = 0;
  #load = JSON.parse('{}');

}

1 Answer 1

3

JavaScript classes are functions, which are objects. (POOP (prototype object-oriented programming)).

Here's an interesting concept, since JavaScript classes are functions, then what do we actually write? JavaScript ES6 classes are just syntactic sugar for prototypes. This means, that both of your ideas are actually the same.
This is exactly how creating a method works.

Here is a good reference: Are ES6 classes just syntactic sugar for the prototypal pattern in Javascript?

Sign up to request clarification or add additional context in comments.

Comments

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.