How to access the "this" of a class with an external function?

Asked

Viewed 53 times

4

I want to create a function within a class that is defined externally, but I can’t access the this class. Example:

class minhaClasse {
  constructor(objeto){
    this.meuNumero = objeto.meuNumero
    this.minhaFuncao = objeto.minhaFuncao;
  }
}

var meuObjeto = new minhaClasse({
  meuNumero: 4,
  minhaFuncao: ()=>{
    console.log(this.meuNumero)
    //log esperado: 4

    this.meuNumero++;
    console.log(this.meuNumero)
    //log esperado: 5
  }
})

meuObjeto.minhaFuncao();

1 answer

7


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 ()

  • 1

    My God, I can’t believe it was such a simple thing. Thank you very much.

  • 1

    @Luíshnrique for nothing, I updated the answer with details about both, Rrow and Function... if you can mark the answer as correct. Grateful

Browser other questions tagged

You are not signed in. Login or sign up in order to post.