Return of a Javascript function

Asked

Viewed 782 times

2

When I run the following code the commands that were to be returned in real are not.

var a = 0;

main = function(_this){
  console.log('Está entrando em Main');
  return function(){
    console.log("Retorno"); //Não escreve o retorno
    a++; //Não incrementa a variável
  };
}(this);

console.log(a);

2 answers

2


Missing calling the function main(). main is a variable that is a function that returns another function, without running it it will do nothing:

var a = 0;
main = function(_this){
  console.log('Está entrando em Main');
  return function(){
    console.log("Retorno"); //Não escreve o retorno
    a++; //Não incrementa a variável
  };
}(this);
main();
console.log(a);

I put in the Github for future reference.

  • Caramba thought that with (this) would already call kkkkkkkkkk Because when I do the following works only with Self-invoking main = Function(_this){ console.log('So it only goes with the call below'); }(this);

  • 1

    You don’t even need the this, but it’s just not returning a function, it’s running a direct.

1

Or if you prefer, you don’t need to call main() after the creation of the function. In time javascript the opportunity to create Self Invoking Functions, which are functions that auto-execute themselves automatically. Just call () at the end of the function.

var a = 0;
main = function(_this){
  console.log('Está entrando em Main');
  return function(){
    console.log("Retorno"); //Não escreve o retorno
    a++; //Não incrementa a variável
  };
}(this)();
console.log(a);
  • Thanks. But I just wanted to understand why you have to call twice. One with this as a parameter (even if not used) and the other without...

  • If you don’t use it within the function then you don’t even need to pass as a parameter, we usually use this type of approach to give bind to this global. That means that within the function you will have access to all this global outside of it, whatever is default language does not happen

  • So the code I’m studying makes it juxtaposing this bind, thank you very much :)

Browser other questions tagged

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