7
To illustrate, 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 innumerable, configurable, or writing ability from being altered, that is to say, transform the essence of the effectively immutable object, as everyone knows, there is the method freeze()
.
But unfortunately, as the following example 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 treat this exception and tone the object Date()
contained in the attribute data_entrada
immutable using ECMA6?
Note: The purpose is that class properties LavarCarro
are read-only. However, the Javascript language - until the current date - does not allow us to use access modifiers. So I use the convention underline ( _ ) attributes of class properties to indicate that they cannot be modified.
I appreciate the answer. About the part of freezing each object I already knew and use the
freeze()
in theDate
I saw in practice that it doesn’t work. The question was precisely to try to find other people’s experiences on the same subject. As if it were a hope in search of another alternative. About the information ofDate
immutable were of great help and added knowledge. Thank you.– DNick
@Djalmamanfrin you can even freeze
Date
partially, replacing all its modifier methods with functions without operation and then freezing it. Partially because there are still ways to modify the date. If you want I can complement the answer with this way.– mercador
you are referring to using the methods
getter
to prevent the attribute from being a value attribute? Example:get dataEntrada(){}
. All knowledge is valid, If you can change thank you.– DNick
@Djalmamanfrin updated the answer.
– mercador
Interesting this last change you added. I will take a look at it calmly and perform some tests.
– DNick