JavaScript习惯用法:仅创建一个函数来调用它 [英] JavaScript idiom: create a function only to invoke it

查看:76
本文介绍了JavaScript习惯用法:仅创建一个函数来调用它的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习 YUI ,偶尔会看到这个成语:

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

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

 < script> 
do abcxyz
< / script>

例如见这里

解决方案

他们正在利用关闭



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



<例如,假设我想创建一个全局唯一的id生成器。有人可能会做这样的代码:

  var counter = 0; 
var genId = function()
{
counter = counter + 1;
返回柜台;
}

然而,现在任何人都可以搞乱计数器,我现在用两个变量(计数器 genId )污染了全局命名空间。



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

  var genId = function()
{
var counter = 0;
var genIdImpl = function()
{
counter = counter + 1;
返回柜台;
}

返回genIdImpl;
}();

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



在YUI的示例代码中,他们只想执行不会污染全局命名空间的代码。


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.

解决方案

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.

这篇关于JavaScript习惯用法:仅创建一个函数来调用它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆