Classes with private Javascript properties

Asked

Viewed 246 times

1

I’m starting my programming frontend, and started messing with classes in Javascript (following the standards set out in Ecmascript 6). But I’m having trouble using private property and methods.

I currently have the following code:

class Negociacao{

  constructor(data, quantidade, valor){

    this.data = data;

    this.quantidade = quantidade;

    this.valor = valor;

    this.volume = quantidade * valor;
  }

  getVolume(){
    return this.volume;
  }

}

The properties data, quantidade, valor and volume are public, but wanted to make them private, and specify their behavior through getters and setters, similar to what I would do with the PHP, or Java. How could I perform the task?

I tried to do it this way, but the data apparently remains public:

class Negociacao{
  data       = 0;
  quantidade = 0;
  valor      = 0;
  volume     = 0;

In this example, the data created outside the constructor remains accessible, even if the contents of the constructor are deleted, unlike the described here.

And, when using let, as in the example below, I see errors "Uncaught Syntaxerror: Unexpected Identifier" and "Uncaught Referenceerror: Trading is not defined":

class Negociacao{
  let data       = 0;
  let quantidade = 0;
  let valor      = 0;
  let volume     = 0;  

Example in PHP of what I want to do:

class Negociacao{
  private $data;
  private $quantidade;
  private $valor;
  private $volume;

  public function __construct(Date $data, int $quantidade, float $valor){
    $this->data       = $data;
    $this->quantidade = $quantidade;
    $this->valor      = $valor;
    $this->volume     = $quantidade * $valor;
  }

  public function __get($propriedade){
    return $this->$propriedade;
  }
}
  • 1

    Arthur, there is the possibility of working with typescript, but I don’t know if it suits you.

  • I know Typescript, but wanted to learn how to work with pure Javascript. Anyway, thanks for the recommendation.

1 answer

1


Today, what exists is a proposal so that there are, in fact, private members of a class. An example is the implementation on V8. And once approved, members will start with #, for example:

class Exemplo {
  #privado = 0;
  get getPrivado() {
    return this.#privado;
  }

  setPrivado(privado) {
    this.#privado = privado;
  }

  #metodoPrivado() {}
}

And a hint, avoid as much as you want to program in an X language in exactly the same way you program in a Y language. Different languages have different patterns and different ways to approach a problem, and although it seems like a good start, Long-term is a bad idea. I recommend reading the Idiomatic.js.

Browser other questions tagged

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