Why call functions from the spot so as not to pollute the general scope of its local variables, if you can just use nesting?

So why do something like that?

var obj = (function(){ function changeColor(){...} ..... return { document.getElementById('id').onclick = changeColor } })() 

If you can do this:

 function colorEl(){ document.getElementById('id').onclick = changeColor function changeColor(){...} } 

    1 answer 1

    In my opinion, the difference is obvious. In the second case, you can call colorEl as colorEl times as you like, while in the first case the call is unique, and it also does not add functions to the global namespace.


    In this case, the example of using (function{}()) contrived and I would even say inappropriate, for more details see here: (function () {}) (); What is this design used for?

    • By the way, in the first version, it will be executed before the DOM processing, that is, document.getElementById ('id') will not work, how to avoid it? - Zow
    • 2
      put the code in domReady or domReady what's the problem? - Specter
    • so it somehow does not look ( - Zow 3:46 pm
    • I do not argue, but the question was about the difference, not the aesthetic side of the application, in this case, the example of using (function{}()) contrived and I would even say inappropriate, for more details see here: (function () {}) (); What is this design used for? - Specter