为什么“(function a() {})”不放“a”进入全局对象?
当回答另一个问题时,我使用这种模式递归地调用函数:
(function() {
// ...
if(should_call_again) arguments.callee();
})();
这有效。我得到的反馈是,命名该函数也有效:
(function func() {
// ...
if(should_call_again) func();
})();
但是,使用这种技术,window.func
是未定义
,这让我感到惊讶。
如果我简单地说,我的问题是:为什么以下内容是正确的?
function a() {}
typeof window.a; // "function"
(function b() {})
typeof window.b; // "undefined"
b
仍然可以在 b
本身内部访问。因此,看起来 ( )
创建了另一个作用域,但事实并非如此,因为只有函数才能创建另一个作用域,而我只是将其包装在 ( )
内。
那么为什么将函数包装在 ( )
内而不将该函数放入全局对象中呢?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
因为您编写的不是函数声明,而是函数表达式。
函数表达式中定义的函数只有在将它们分配给变量时才会存储在某个地方;你没有那样做;你立即调用它。
在[非常宽松!]的意义上,您可以将函数声明视为函数表达式赋值的特殊形式:
这仍然不是严格准确的比较,但它可能有助于理解函数声明这是一件很特别的事情。
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:
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:
It is actually written out as: (note the extra set of parenthases on the end)
When you write a function like this, it is immediately invoked and yet still carries its own scope.