Returning a JavaScript function

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);
    
asked by anonymous 28.07.2017 / 04:12

2 answers

2

The main() function is missing. main is a variable that is a function that returns another function, without executing it it will not do anything:

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 placed GitHub for future reference .

    
28.07.2017 / 04:25
1

Or if you prefer, you do not need to call main () after the function is created. In javascript we do not have the opportunity to create Self Invoking Functions, which are functions that auto run 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);
    
01.08.2017 / 14:14