为什么“(function a() {})”不放“a”进入全局对象?

发布于 2024-11-29 09:11:28 字数 817 浏览 2 评论 0原文

回答另一个问题时,我使用这种模式递归地调用函数:

(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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

兲鉂ぱ嘚淚 2024-12-06 09:11:28

因为您编写的不是函数声明,而是函数表达式

函数表达式中定义的函数只有在将它们分配给变量时才会存储在某个地方;你没有那样做;你立即调用它。


在[非常宽松!]的意义上,您可以将函数声明视为函数表达式赋值的特殊形式:

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

这仍然不是严格准确的比较,但它可能有助于理解函数声明这是一件很特别的事情。

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.

伴梦长久 2024-12-06 09:11:28

您似乎忽略了一个微妙的区别,而不是将函数定义为:

(function b () { });

它实际上写为:(注意末尾的额外括号)

(function b () { }());

当您编写这样的函数时,它会立即被调用并且但仍然有其自己的范围。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文