How many globals make sense to be passed to the IIFE wrapper?

后端 未结 3 438
我寻月下人不归
我寻月下人不归 2021-01-22 12:39

To which extent does it make sense to pass plenty of global values to an IIFE?

The common thing is just to pass 3 as far as I see everywhere (window, document and undefi

3条回答
  •  生来不讨喜
    2021-01-22 12:55

    First of all, those values are not IIFEs.

    And this is not about “saving characters” by having shorter variables names inside the function (at least not mainly), but rather about variable lookup and the “cost” associated with it.

    If you were to use f.e. document inside your function without passing it in, then first a variable named document would be searched in the scope of the function, and only when that fails, search would continue in the scope above that, and so on.

    That is the reason for passing such objects as parameters into the function – so that a direct reference to them within the function scope exists, and they do not have to be looked up in higher outside scopes.

    Sometimes, you might even see this used in such a form like this:

    (function(document) {
      // do something with document, such as:
      document.foo();
      document.bar = "baz";
    })(document);
    

    – in that form, it should be even more clear that this is not about saving characters in variable names. The object is still referred to as document inside the function (which makes it clear what it is supposed to represent – the global document object), and the only effect achieved by this is said shorter lookup.

提交回复
热议问题