0

I have something similar to the code below:

var msg="first call";
(function test(msg)
    {
        console.log("inside self call");
    }
)();

msg="second call";
console.log("before inline call");
test(msg);
console.log("after inline call");

Where I need to call a function (that is self-invoked at the beginning of the code).

It seems to me that I can not call a self-invoked function. But I am not sure as this is the first time I face such situation. This is the output I'm getting in the console:

inside self call
before inline call
ReferenceError: test is not defined

Is there a way other than repeating the function code with another name?

user6875880
  • 651
  • 1
  • 7
  • 17
  • 1
    Why don't you split declaration and first invokation? – Yury Tarabanko Jun 29 '17 at 08:44
  • In [*old versions of IE*](https://kangax.github.io/nfe/#jscript-bugs), function expressions with a name became global functions, so actually it will work in some (faulty) browsers. ;-) – RobG Jun 29 '17 at 08:47
  • Not using an IIFE in the first place would be the most sensible approach. Use a function declaration, then call that function. Later: call it again. – Quentin Jun 29 '17 at 08:53

1 Answers1

0

The self invoking function expression has its own scope
This article describe and gives a work around:
https://christierney.com/2012/09/05/accessing-javascript-methods-from-outside-its-self-invoking-function-wrapper/

Let’s say you have a method you want to be globally accessible, but want a self-invoking function around it to make sure it’s jQuery $ alias safe.

In this example, the following code is in global.js:

(function( $ ) {
   function showLoader( cfg ) {
      if( cfg == 'show') {
         $( '.loader' ).show();
      } else //more code...
   }
})(jQuery);

In this example, the following code is in myPage.js:

(function($) {
   showLoader( 'show' );
})(jQuery);

You will find that myPage.js cannot access the showLoader() method even though global.js was called first in the HTML page.

The fix for this is to push the showLoader() method out to the window (global) scope:

(function( $ ) {
   window.showLoader = function( cfg ) {
      if( cfg == 'show') {
         $( '.loader' ).show();
      } else //more code...
   }
})(jQuery);

By assigning the function to the window scope it is now globally accessible. Just remember that it is now no longer protected by the closure but it still has access to the jQuery $ alias.

Amr Elgarhy
  • 66,568
  • 69
  • 184
  • 301
  • it's not the self invoking function has an own scope, rather the expresssion has an own scope. you could use a named self invoking function and use it as a recusion inside, with the given name. the name exists only in the expression's scope. – Nina Scholz Jun 29 '17 at 08:57
  • @NinaScholz Yes definitely you are right, thanks, I will update my answer – Amr Elgarhy Jun 29 '17 at 09:00