How to declare global variables when using the strict mode pragma

前端 未结 5 1504
梦如初夏
梦如初夏 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 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.

提交回复
热议问题