JavaScript 习惯用法:创建一个函数只是为了调用它

发布于 2024-07-15 11:18:13 字数 409 浏览 3 评论 0原文

我正在学习 YUI 并且偶尔会看到这个习语:

 <script>
     (function x(){ do abcxyz})();
 </script>

为什么他们创建一个函数只是为了调用它? 为什么不直接写:

<script>
    do abcxyz
</script>

例如,请参见此处

I am learning YUI and have occasionally seen this idiom:

 <script>
     (function x(){ do abcxyz})();
 </script>

Why do they create a function just to invoke it?
Why not just write:

<script>
    do abcxyz
</script>

For example see here.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(2

反话 2024-07-22 11:18:13

他们正在利用闭包

简短说明:由于 JS 使用函数级作用域,因此您可以在函数内执行一系列操作并使其保留在该作用域内。 这对于调用不会扰乱全局命名空间的代码很有用。 它还允许创建私有变量 - 如果您在匿名函数内部声明一个变量并立即执行它,则只有匿名函数内部的其他代码可以访问该变量。

例如,假设我想制作一个全局唯一的 id 生成器。 人们可能会编写这样的代码:

var counter = 0;
var genId = function()
{
    counter = counter + 1;
    return counter;
}

但是,现在任何人都可以搞乱 counter,而且我现在用两个变量(countergenId< /em>)。

相反,我可以使用匿名函数来生成计数器函数:

var genId = function()
{
    var counter = 0;
    var genIdImpl = function()
    {
        counter = counter + 1;
        return counter;
    }

    return genIdImpl;
}();

现在,我在全局命名空间中只有一个变量,这是有利的。 更重要的是,计数器变量现在可以安全地被修改——它只存在于匿名函数的作用域中,因此只有函数 genIdImpl (在同一作用域中定义)可以访问它。

看起来在 YUI 的示例代码中,他们只是想执行根本不污染全局命名空间的代码。

They're taking advantage of closures.

A short explanation: Since JS uses function-level scoping, you can do a bunch of actions within a function and have it remain in that scope. This is useful for invoking code that doesn't mess with the global namespace. It also allows one to make private variables - if you declare a variable inside of an anonymous function and execute it immediately, only other code inside of the anonymous function can access that variable.

For example, suppose I want to make a global unique id generator. One might do code like this:

var counter = 0;
var genId = function()
{
    counter = counter + 1;
    return counter;
}

However, now anyone can mess with counter, and I've now polluted the global namespace with two variables (counter and genId).

Instead, I could use a anonymous function to generate my counter function:

var genId = function()
{
    var counter = 0;
    var genIdImpl = function()
    {
        counter = counter + 1;
        return counter;
    }

    return genIdImpl;
}();

Now, I only have one variable in the global namespace, which is advantageous. More importantly, the counter variable is now safe from being modified - it only exists in the anonymous function's scope, and so only the function genIdImpl (which was defined in the same scope) can access it.

It looks like in YUI's example code, they just want to execute code that doesn't pollute the global namespace at all.

尐籹人 2024-07-22 11:18:13

我猜他们想避免命名空间冲突。 在 JS 中似乎是一个很好的实践。

They want to avoid namespace collisions, I'd guess. Seems as a good practice in JS.

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