0

I've found an interesting method of defining functions:

! function() {
  function myFunction() {
    return returnValue;
  }
}();

However, this function can not be called directly from the browser console, how could I achieve it?

Aslanex
  • 79
  • 2
  • 9
  • 1
    It's anonymous -- you can't. If you need to call it whenever, you need to define it. – Jeremy Jackson Oct 27 '16 at 13:47
  • 1
    http://benalman.com/news/2010/11/immediately-invoked-function-expression/#iife - an interesting read about IIFEs – evolutionxbox Oct 27 '16 at 13:48
  • you need to assign its reference to a variable first. – gurvinder372 Oct 27 '16 at 13:49
  • 1
    You can't call it because it's been scoped to your outer function. That's one reason why you do this, to stop the pollution of higher levels with functions/variables they don't need to know about. This really sounds like an [XY Problem](http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem) - what do you want to actually achieve? – James Thorpe Oct 27 '16 at 13:49
  • Anonymous functions are nameless, so if you do not assign them to a var, they will execute and will not have a handle to them. They are great for scope control and one off executions. Otherwise you have to return sometime and assign it to a var handle or something similar. – scheppsr77 Oct 27 '16 at 13:50
  • That was just an academical question – I saw an app using this method and wanted to play with it and learn how it works, which is explained in the Serban's answer. Thanks. – Aslanex Oct 29 '16 at 16:41

1 Answers1

1

That is an IIFE (immediately invoked function expression) wrapped around your function.

I would suggest using this approach for the code that you've written:

!function() {
  function myFunction() {
    return 'hello';
  }

  window['myFunction'] = myFunction;
}();

Now call myFunction in the console. Previously myFunction was hidden inside your IIFE and was not exposed as a global.

Șerban Ghiță
  • 1,899
  • 20
  • 21