Search code examples
javascriptecmascript-5

Why javascript function parentheses can not access the outside?


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

Solution

  • 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!