开发者

Why does '(function a() {})' not put 'a' into the global object?

开发者 https://www.devze.com 2023-03-27 23:24 出处:网络
When answering another question, I was using this pattern to call a function recursively: (function() {

When answering another question, I was using this pattern to call a function recursively:

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

which worked. I got feedback that naming the function 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 be accessible inside b itself. So it seems like the ( ) create another scope, but that cannot be the case because only functions create another scope, and I'm 开发者_开发知识库just wrapping it inside ( ).

So why does wrapping a function inside ( ) not put the function into the global object?


Because you're not writing a function declaration, but a function expression.

Functions defined in function expressions only get stored someplace when you assign them to a variable; you did not do that; you just called it immediately.


In a [very loose!] sense, you could think of 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 may help in understanding that a function declaration is kind of a special thing.


There is a subtle difference that you appear to have overlooked, instead of defining the function as:

(function b () { });

It is actually written out as: (note the extra set of parenthases on the end)

(function b () { }());

When you write a function like this, it is immediately invoked and yet still carries its own scope.

0

精彩评论

暂无评论...
验证码 换一张
取 消