JavaScript idiom: create a function only to invoke it

[亡魂溺海] 提交于 2019-12-05 11:23:58

问题


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.


回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/698548/javascript-idiom-create-a-function-only-to-invoke-it

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!