Actually, updates the object yes. See:
class Endereco {
constructor(rua, cidade) {
this.rua = rua;
this.cidade = cidade;
this.exibirEndereco = function() {
console.log(`Endereço: ${rua}, ${cidade}.`);
};
}
}
const avBr = new Endereco('Avenida Brasil', 'Belo Horizonte');
console.log(avBr);
avBr.cidade = 'Rio de Janeiro';
console.log(avBr); // atualizou a propriedade cidade
The problem occurs in view of where the variables used by the method exibirEndereco
arose.
Note that within the function exibirEndereco
, so much rua
how much cidade
do not refer to the properties of the Endereco
, but yes of the constructor’s parametric variables.
Therefore, even if you change the instance variables, the function exibirEndereco
, created during the building of the object, it will keep its variables unchanged (since the variables you passed to the constructor have not been changed). Remember that Javascript primitives, like string
, are immutable.
To fix this problem, make the method exibirEndereco
depends on instance variables. You can access these variables under qualification this
(which, in such a situation, refers to the).
Another idea is not to declare the method in the constructor, but in the class itself. See:
class Endereco {
constructor(rua, cidade) {
this.rua = rua;
this.cidade = cidade;
}
exibirEndereco() {
// ↓↓↓↓ ↓↓↓↓
console.log(`Endereço: ${this.rua}, ${this.cidade}.`);
}
}
const avBr = new Endereco('Avenida Brasil', 'Belo Horizonte');
avBr.exibirEndereco(); // Endereço: Avenida Brasil, Belo Horizonte
avBr.cidade = 'Rio de Janeiro';
avBr.exibirEndereco(); // Endereço: Avenida Brasil, Rio de Janeiro
The advantage of this way to define the method is that by attaching to the function the this
During construction, you generate a new function for each instance. Methods defined directly in the class are associated with the prototype of the constructor and are therefore reused by all instances. Learn more about prototypes here.
Very good answer! ask me a question.. is only for Javascript? or is included other languages too?
– gleisin-dev
Thanks, @gleisin-dev! : )) I can’t say for sure since this is something that depends a lot on each language... But, in general, I think the difference between consuming a parametric variable and an instance variable can cause this kind of problem in several languages.
– Luiz Felipe
I will pay attention when declaring these methods, mainly in [tag:php].. turns and meche to pego rsrs!
– gleisin-dev