Create variable javascript constructors

Asked

Viewed 60 times

1

Lately I’m creating javascript classes defining what I don’t want to be public during the constructor, using Noughtclass.myVariable ex:

class NovaClasse {
  static podeMexer = false
  constructor(){
    NovaClasse.estatica = 'nao me toque'
  }
  retornaEstatica(){ return NovaClasse.estatica }
  seMexeu(){ return NovaClasse.podeMexer }
}
NovaClasse.estatica = 'mexi contigo'
NovaClasse.podeMexer = true
const teste = new NovaClasse()
console.log(
  teste.retornaEstatica(), // continua "não me toque"
  teste.seMexeu() //true. alterou
)

In my tests I realized that if I change the value of a static, the class will be instantiated with the new values; it is only this situation that the way I have been doing seeks to avoid. In my way of thinking, if I can change without having to extend then creating classes loses some sense

As I didn’t see any other example using this "technique" and not to make this a question opinionated and hurt the rules of the site then ...

What are the problems I may have creating static during the constructor?

  • 3

    In fact, of the two forms you changed the value; however, NovaClasse.estatica you set again when the class is again instantiated, overriding the value you have just set. And yes, if you only use classes with static values, it loses its meaning. They are a mechanism for you to group heterogeneous information that belongs to the same instance. If static is the same for all, I wouldn’t need class.

  • 1

    By default classes do not have a private property or method so static is public, there is a proposal for such but still under discussion. What you can do is use Symbol() as a "hack" to arrive at this behavior (private)

  • Thank you, I will seek understanding about Symbol. Then I ended up observing that if changing the property in the class after things instantiated, also alters the instances, which falls by the way my intention to protect the variables. I don’t think we can take any more notes on that question, the moderator can close it

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.