JavaScript idiom: create a function only to invoke it

前端 未结 2 1554
伪装坚强ぢ
伪装坚强ぢ 2021-02-19 01:37

I am learning YUI and have occasionally seen this idiom:

 

Why do they create

相关标签:
2条回答
  • 2021-02-19 02:04

    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.

    0 讨论(0)
  • 2021-02-19 02:12

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

    0 讨论(0)
提交回复
热议问题