Why doesn't the (function a () {}) 'put' a 'in the global object?

When answering another question, I used this template to call a function recursively:

(function() { // ... if(should_call_again) arguments.callee(); })(); 

who worked. I got the feedback that function naming also worked:

 (function func() { // ... if(should_call_again) func(); })(); 

However, with this technique, window.func is undefined , which came as a surprise to me.

If I put it simply, my question is: why is the following true?

 function a() {} typeof window.a; // "function" (function b() {}) typeof window.b; // "undefined" 

b is still available inside b . So it seems that ( ) creates a different scope, but this cannot be because only functions create a different scope, and I just wrap it inside ( ) .

So why doesn't wrapping a function inside ( ) put a function in a global object?

+4
source share
2 answers

Because you are not writing a function declaration, but a function expression.

Functions defined in function expressions are only stored somewhere when you assign them to a variable; you did not do this; you just called him immediately.


In the sense of [very free!] You can consider function declarations as a special form of function expression assignment:

 function a() {} // vs: var a = function() {}; 

This is still not a strictly accurate comparison, but it can help to understand that a function declaration is something special.

+5
source

There is a subtle difference that you seem to have missed, instead of defining a function as:

 (function b () { }); 

This is actually written as: (pay attention to the additional set of partases at the end)

 (function b () { }()); 

When you write such a function, it is immediately called and still carries its own scope.

0
source

All Articles