Awkward way of executing JavaScript code

This question already has an answer here:

  • How do JavaScript closures work? 88 answers
  • Why is this function wrapped in parentheses, followed by parentheses? [duplicate] 6 answers

  • This is a poor example. Consider the following:

    var a = (function(){
        var ret = {};
        ret.test = "123";
        function imPrivate() { /* ... */ }
        ret.public = function() { imPrivate(); }
        return ret;
    })();
    

    a will contain the varible test and the function public, however you can not access imPrivate. This is the common way to handle public vs private variables;

    See Why is this function wrapped in parentheses, followed by parentheses? for more info.


    var a = (function() {
      return foo(bar);
    })();
    

    In this case this is really unnecessary, but this is not wrong and it will not throw an error.

    But IIF some times uses like module pattern :

    var a = (function() {
      /* some other code in own scope */
      return foo(bar);
    })();
    

    In this case IIF is just a module which exports something outside.


    The closure function is used to encapsulate some of the attributes / methods in the function. Much like the private / public principle from other languages.

    You can find more on this topic here under Module Pattern

    链接地址: http://www.djcxy.com/p/1472.html

    上一篇: 我的JavaScript范围有什么问题?

    下一篇: 执行JavaScript代码的尴尬方式