Change the Arrow-Function:
minhaFuncao: () => {
by normal Function:
minhaFuncao: function () {
Thus:
class minhaClasse {
constructor(objeto){
this.meuNumero = objeto.meuNumero
this.minhaFuncao = objeto.minhaFuncao;
}
}
var meuObjeto = new minhaClasse({
meuNumero: 4,
minhaFuncao: function () {
console.log(this.meuNumero)
//log esperado: 4
this.meuNumero++;
console.log(this.meuNumero)
//log esperado: 5
}
})
meuObjeto.minhaFuncao();
Although it has become fashionable to use Arrow-Function and to have people thinking that this is the new way of doing things is a mistake, in fact Arrow-Function has a specific reason to exist, outside facilitate a little the use of the Return, Arrow provides access to the context of the location that is "declared" as if it belonged to the same context, ie if you have a this
outside the function it will be accessible (which is not the case of what you used, it is different)
For example:
function Foo()
{
this.foo = 1000;
function bar() {
return this.foo; //Não vai funcionar, será undefined
}
this.response = bar();
}
let teste = new Foo;
console.log(teste.response);
While with Arrow will be accessible:
function Foo()
{
this.foo = 1000;
var bar = () => {
return this.foo; //Vai funcionar, será 1000
};
this.response = bar();
}
let teste = new Foo;
console.log(teste.response);
This could also be a return
implicit":
var bar = () => this.foo;
That is to say, function ()
is not obsolete, nor ceased to be used, it is simply that both has time and place to use, as it was in the case of your code, the correct one to use is function ()
My God, I can’t believe it was such a simple thing. Thank you very much.
– Luís HNrique
@Luíshnrique for nothing, I updated the answer with details about both, Rrow and Function... if you can mark the answer as correct. Grateful
– Guilherme Nascimento