Is it possible to call an anonymous function?

Asked

Viewed 565 times

3

I wonder if it is possible to call an anonymous function outside her scope.

When I call the function, this error occurs:


Uncaught TypeError: consomeCsr is not a function

Example:

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

        consomeCsr();

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. That IIFE is run immediately and the variable consomeCsr receives the value of undefined, which is what the alert cue/return.

If you want to have a function that runs this Alert then you must 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 so you can return and reuse it like this:

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

jsFiddle: http://jsfiddle.net/5q3L1xdr/1/

Browser other questions tagged

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