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

后端 未结 3 464
我寻月下人不归
我寻月下人不归 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:58

    There are a number of cases where it makes sense to pass variables to an IIFE.

    Aliasing

    Passing a variable to an IIFE allows you to rename the variable within the function. This is commonly seen when using jQuery, particularly when noConflict is used:

    (function ($) {
       //in here $ will be the same as jQuery
    }(jQuery));
    

    Aliasing also helps minifiers to minify code, when you see something like:

    (function (document, slice, Math) {
        ...
    }(document, Array.prototype.slice, Math));
    

    The minifier can rename the parameters to whatever it wants, and save you bytes. For large scripts using these properties a lot, it can be significant savings when it gets turned into:

    (function(a,b,c){...}(document,Array.prototype.slice,Math));
    

    Portability

    This is more of an edge case than a general rule, but it's common to see a global IIF in the form of:

    (function (global /* or window */) {
        ...
    }(this));
    

    This allows for portability between node.js and the browser so that the global variable has the same name in both environments.

    Character Savings

    While I already mentioned that minifiers can reduce the character count by changing the names of aliases, you may want to do this manually if you're participating in a code golf challenge.

    Reference Safety

    If you're authoring a script that must work in whatever environment its dumped into (think google analytics), you'll want to be sure that the global methods you're calling are what you expect. Storing a reference to those functions by passing them as parameters is one way to preserve the reference to the functions from becoming overridden by a malicious or ignorant programmer.


    To answer the question in your title:

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

    As many as you need and no more. If you need to alias one or two variables, pass one or two references. If you need to be sure that the global functions aren't being changed, you may end up with 100 parameters. There's no hard-and-fast rule on this.

提交回复
热议问题