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;
}
}
Arthur, there is the possibility of working with typescript, but I don’t know if it suits you.
– Daniel Mendes
I know Typescript, but wanted to learn how to work with pure Javascript. Anyway, thanks for the recommendation.
– Arthur Siqueira