How to declare global variables when using the strict mode pragma

前端 未结 5 1451
梦如初夏
梦如初夏 2021-01-31 16:52

It\'s considered good practice to use a self-invoking function to wrap strict mode compliant code, often called the strict mode pragma:

(function(){
  \"use stri         


        
相关标签:
5条回答
  • 2021-01-31 16:58

    Benefit of alt 2 and 3 is that they keep all of the code inside the "container function." One line of code outside of the function is easy to miss when reading the code.

    Also:

    • "GLOB" should be the application's name. -- You want to allow for more than one application per html/js file without name collisions.
    0 讨论(0)
  • 2021-01-31 17:05

    Andrea Giammarchi has a nice technique for doing this, that works across browsers. Define a function in your self-invoking function called globalEval like so:

    (function () {
        "use strict";
        function globalEval(data) {
            data = data.replace(/^\s*|\s*$/g, "");
            if (data) {
                var head = document.getElementsByTagName("head")[0] || document.documentElement,
                    script = document.createElement("script");
                script.type = "text/javascript";
                script.text = data;
                head.appendChild(script);
                head.removeChild(script);
            }
        }
    
        // use globalEval to stick variables into the global scope
        globalEval("var myGlobal = 1;");
        // myGlobal === 1
    )();
    // myGlobal === 1
    

    Or define the globalEval function outside of the self-invoking code if you want to use it in other scopes.

    0 讨论(0)
  • 2021-01-31 17:14

    IMO alternative 3 is best. But it assumes that window represents the global scope - which is true for the browser but not for other JS environments (command line, Node.js, etc.).

    The following will work across the board:

    (function(globals){
      "use strict";
      globals.GLOB = {};
    }(this));
    
    0 讨论(0)
  • 2021-01-31 17:16

    Method 1 would fail if it's pasted in another function.

    Using method 3, it is easier to export your methods to another namespace. Simply replacing window with, say, frames[0] or document is enough to attach all methods to a custom namespace.

    I recommend method 3, for the last reason.

    0 讨论(0)
  • 2021-01-31 17:22

    I know this is an old question but there's one not mentioned way of getting global context:

    (function(globals){
      "use strict";
      globals.GLOB = {};
    }( (1,eval)('this') ));
    

    (1,eval)('this')

    will evaluate this from global context, so you can paste this wherever you like and you will always get global context

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