0

I'm curious, why not just javascript function scope it? Why just add a parenthesis can not access it? My guess is that the parentheses and javascript related operations, but do not know exactly why this child principle and design?

(function test(){
    console.log( test );
})();
test();//Uncaught ReferenceError: test is not defined  IE8- is ok

or

(function test(){
    console.log( test );
});
test();//Uncaught ReferenceError: test is not defined  IE8- is ok
Wang Xiao
  • 167
  • 2
  • 13
  • 4
    That's how an Immediately Invoked Function Expression work, it's only availble inside it's own scope. – adeneo Apr 27 '15 at 12:56
  • IE8 would have failed on the console.log, as this is not supported in IE8. – Paddy Apr 27 '15 at 12:58
  • 1
    The first link in the duplicates list is misleading. This has nothing to do with closures. See the second link about function expressions. – g.kertesz Apr 27 '15 at 13:12

2 Answers2

2

When you wrap a function in parentheses like you did, it does put it in a new scope.

It also acts like a return value, which is why it can be called as an IIFE, or Immediately Invoking Function Expression.

Another way to re-write it, which will make more sense is like so:

var myFunc = (function test(){
  alert('Hello!');
});

myFunc(); // Works!
test();   // Doesn't work!
Jim Buck
  • 2,326
  • 24
  • 38
-1

To learn more about this, you should read about IIFE - Immediately-invoked function expression.

The short version - the function runs in its own scope, unless you pass parameters to it, like so:

(function test(x) {
   alert(x); //alerts "yey!";
})("yey!"); 
Omri Aharon
  • 16,589
  • 4
  • 37
  • 56