For example, I have the following class:
class LavarCarro {
constructor(cor, placa, data_entrada) {
this._cor = cor;
this._placa = placa;
this._data_entrada = data_entrada;
Object.freeze(this); // congela a instância do objeto
}
get cor() {
return this._cor;
}
get placa() {
return this._placa;
}
get dataEntrada() {
return this._data_entrada;
}
}
To prevent existing properties, or their innumerability, configurability, or writing ability from being changed, ie transforming the essence of the object effectively immutable, as everyone knows, there is the freeze()
method.
But unfortunately, as the example below shows that object-type values in a frozen object can be changed ( freeze is shallow).
var data = new LavarCarro('Preto', 'ABC1234', new Date());
console.log(data.dataEntrada);
//Mon Jul 10 2017 08:45:56 GMT-0300 (-03) - Resultado do console
data.dataEntrada.setDate(11);
console.log(data.dataEntrada);
//Tue Jul 11 2017 08:45:56 GMT-0300 (-03) - Resultado do console
How can I handle this exception and tune the Date()
object contained in the% immutable data_entrada
fault attribute using ECMA6?
Note: The goal is for the properties of the LavarCarro
class to be read-only. However, the JavaScript language - until the current date - does not allow us to use access modifiers. So I use the underline (_) convention in the class properties attributes to indicate that they can not be modified.