Is it possible to call an anonymous function?

3

I wonder if it's possible to call an anonymous function out of its scope.

When I call the function, this error occurs:

Uncaught TypeError: consomeCsr is not a function

Example:

  consomeCsr = (function () {
     alert('Funcção Anonima')
        })();

        consomeCsr();
    
asked by anonymous 05.10.2015 / 18:28

1 answer

4

It is not possible to call an anonymous function if it is not assigned to a variable.

In your example:

consomeCsr = (function () {
  return alert('Funcção Anonima')
})();

consomeCsr();

consomeCsr is not a function. This IIFE is run immediately and the variable consomeCsr receives the value of undefined , which is what the alert leaves / returns.

If you want to have a function that runs this alert then you should have:

var consomeCsr = function () {
  alert('Funcção Anonima');
};

But if you want a self-executing function ( IIFE ) but also stay in a variable to use later, you have to give it a name to be able to return and reuse like this:

var consomeCsr = (function autoExecutavel() {
    alert('Funcção Anonima');
    return autoExecutavel;
})();

jsFiddle: link

    
05.10.2015 / 18:31