如何避免JavaScript中的全局变量?

Jos*_*ola 75 javascript global-variables

我们都知道全局变量不是最佳实践.但有几个例子,没有它们很难编码.您使用什么技术来避免使用全局变量?

例如,给定以下场景,您将如何使用全局变量?

JavaScript代码:

var uploadCount = 0;

window.onload = function() {
    var frm = document.forms[0];

    frm.target = "postMe";
    frm.onsubmit = function() {
        startUpload();
        return false;
    }
}

function startUpload() {
    var fil = document.getElementById("FileUpload" + uploadCount);

    if (!fil || fil.value.length == 0) {
        alert("Finished!");
        document.forms[0].reset();
        return;
    }

    disableAllFileInputs();
    fil.disabled = false;
    alert("Uploading file " + uploadCount);
    document.forms[0].submit();
}
Run Code Online (Sandbox Code Playgroud)

相关标记:

<iframe src="test.htm" name="postHere" id="postHere"
  onload="uploadCount++; if(uploadCount > 1) startUpload();"></iframe>

<!-- MUST use inline JavaScript here for onload event
     to fire after each form submission. -->
Run Code Online (Sandbox Code Playgroud)

此代码来自具有多个的Web表单<input type="file">.它一次上传一个文件以防止大量请求.它通过POST到iframe,等待触发iframe onload的响应,然后触发下一次提交来完成此操作.

您不必专门回答这个例子,我只是提供它来参考我无法想到避免全局变量的方法.

eye*_*ess 64

最简单的方法是将代码包装在一个闭包中,并手动将全局需要的变量公开给全局范围:

(function() {
    // Your code here

    // Expose to global
    window['varName'] = varName;
})();
Run Code Online (Sandbox Code Playgroud)

解决Crescent Fresh的评论:为了完全从场景中删除全局变量,开发人员需要更改问题中假设的一些事项.看起来会更像这样:

使用Javascript:

(function() {
    var addEvent = function(element, type, method) {
        if('addEventListener' in element) {
            element.addEventListener(type, method, false);
        } else if('attachEvent' in element) {
            element.attachEvent('on' + type, method);

        // If addEventListener and attachEvent are both unavailable,
        // use inline events. This should never happen.
        } else if('on' + type in element) {
            // If a previous inline event exists, preserve it. This isn't
            // tested, it may eat your baby
            var oldMethod = element['on' + type],
                newMethod = function(e) {
                    oldMethod(e);
                    newMethod(e);
                };
        } else {
            element['on' + type] = method;
        }
    },
        uploadCount = 0,
        startUpload = function() {
            var fil = document.getElementById("FileUpload" + uploadCount);

            if(!fil || fil.value.length == 0) {    
                alert("Finished!");
                document.forms[0].reset();
                return;
            }

            disableAllFileInputs();
            fil.disabled = false;
            alert("Uploading file " + uploadCount);
            document.forms[0].submit();
        };

    addEvent(window, 'load', function() {
        var frm = document.forms[0];

        frm.target = "postMe";
        addEvent(frm, 'submit', function() {
            startUpload();
            return false;
        });
    });

    var iframe = document.getElementById('postHere');
    addEvent(iframe, 'load', function() {
        uploadCount++;
        if(uploadCount > 1) {
            startUpload();
        }
    });

})();
Run Code Online (Sandbox Code Playgroud)

HTML:

<iframe src="test.htm" name="postHere" id="postHere"></iframe>
Run Code Online (Sandbox Code Playgroud)

不需要内联事件处理程序<iframe>,它仍将使用此代码触发每个加载.

关于加载事件

这是一个测试用例,表明您不需要内联onload事件.这取决于在同一服务器上引用文件(/emptypage.php),否则您应该只能将其粘贴到页面中并运行它.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title>untitled</title>
</head>
<body>
    <script type="text/javascript" charset="utf-8">
        (function() {
            var addEvent = function(element, type, method) {
                if('addEventListener' in element) {
                    element.addEventListener(type, method, false);
                } else if('attachEvent' in element) {
                    element.attachEvent('on' + type, method);

                    // If addEventListener and attachEvent are both unavailable,
                    // use inline events. This should never happen.
                } else if('on' + type in element) {
                    // If a previous inline event exists, preserve it. This isn't
                    // tested, it may eat your baby
                    var oldMethod = element['on' + type],
                    newMethod = function(e) {
                        oldMethod(e);
                        newMethod(e);
                    };
                } else {
                    element['on' + type] = method;
                }
            };

            // Work around IE 6/7 bug where form submission targets
            // a new window instead of the iframe. SO suggestion here:
            // http://stackoverflow.com/q/875650
            var iframe;
            try {
                iframe = document.createElement('<iframe name="postHere">');
            } catch (e) {
                iframe = document.createElement('iframe');
                iframe.name = 'postHere';
            }

            iframe.name = 'postHere';
            iframe.id = 'postHere';
            iframe.src = '/emptypage.php';
            addEvent(iframe, 'load', function() {
                alert('iframe load');
            });

            document.body.appendChild(iframe);

            var form = document.createElement('form');
            form.target = 'postHere';
            form.action = '/emptypage.php';
            var submit = document.createElement('input');
            submit.type = 'submit';
            submit.value = 'Submit';

            form.appendChild(submit);

            document.body.appendChild(form);
        })();
    </script>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

每次单击Safari,Firefox,IE 6,7和8中的提交按钮时,警报都会触发.

  • 当人们投票给他们解释他们投票的理由时,它会很有帮助. (3认同)
  • 我没有投票.但是,说window ['varName'] = varName与在闭包之外进行全局var声明相同.`var foo ="bar"; (function(){alert(window ['foo'])})();` (3认同)

ere*_*non 56

我建议模块模式.

YAHOO.myProject.myModule = function () {

    //"private" variables:
    var myPrivateVar = "I can be accessed only from within YAHOO.myProject.myModule.";

    //"private" method:
    var myPrivateMethod = function () {
        YAHOO.log("I can be accessed only from within YAHOO.myProject.myModule");
    }

    return  {
        myPublicProperty: "I'm accessible as YAHOO.myProject.myModule.myPublicProperty."
        myPublicMethod: function () {
            YAHOO.log("I'm accessible as YAHOO.myProject.myModule.myPublicMethod.");

            //Within myProject, I can access "private" vars and methods:
            YAHOO.log(myPrivateVar);
            YAHOO.log(myPrivateMethod());

            //The native scope of myPublicMethod is myProject; we can
            //access public members using "this":
            YAHOO.log(this.myPublicProperty);
        }
    };

}(); // the parens here cause the anonymous function to execute and return
Run Code Online (Sandbox Code Playgroud)

  • @Josh:全局变量不是邪恶的.全局变量__是邪恶的.保持全局变量的数量尽可能少. (10认同)
  • 我会+1,因为我理解这一点并且它非常有用,但我仍然不清楚在我只使用一个全局变量的情况下这会有多有效.如果我错了,请纠正我,但执行此函数并返回它会导致返回的对象存储在`YAHOO.myProject.myModule`中,这是一个全局变量.对? (3认同)

Jus*_*son 7

首先,不可能避免使用全局JavaScript,有些东西总是悬在全球范围内.即使您创建了一个名称空间,这仍然是一个好主意,该名称空间将是全局的.

但是,有许多方法不滥用全球范围.两个最简单的方法是使用闭包,或者因为你只需要跟踪一个变量,只需将它设置为函数本身的属性(然后可以将其视为static变量).

关闭

var startUpload = (function() {
  var uploadCount = 1;  // <----
  return function() {
    var fil = document.getElementById("FileUpload" + uploadCount++);  // <----

    if(!fil || fil.value.length == 0) {    
      alert("Finished!");
      document.forms[0].reset();
      uploadCount = 1; // <----
      return;
    }

    disableAllFileInputs();
    fil.disabled = false;
    alert("Uploading file " + uploadCount);
    document.forms[0].submit();
  };
})();
Run Code Online (Sandbox Code Playgroud)

*请注意,uploadCount此处内部正在进行递增

功能属性

var startUpload = function() {
  startUpload.uploadCount = startUpload.count || 1; // <----
  var fil = document.getElementById("FileUpload" + startUpload.count++);

  if(!fil || fil.value.length == 0) {    
    alert("Finished!");
    document.forms[0].reset();
    startUpload.count = 1; // <----
    return;
  }

  disableAllFileInputs();
  fil.disabled = false;
  alert("Uploading file " + startUpload.count);
  document.forms[0].submit();
};
Run Code Online (Sandbox Code Playgroud)

我不确定为什么uploadCount++; if(uploadCount > 1) ...有必要,因为看起来条件总是如此.但是如果你确实需要对变量进行全局访问,那么上面描述的函数属性方法将允许你这样做,而变量实际上不是全局变量.

<iframe src="test.htm" name="postHere" id="postHere"
  onload="startUpload.count++; if (startUpload.count > 1) startUpload();"></iframe>
Run Code Online (Sandbox Code Playgroud)

但是,如果是这种情况,那么您应该使用对象文字或实例化对象,并以正常的OO方式进行此操作(如果它可以使用模块模式,则可以使用模块模式).

  • 你绝对可以避免全局作用域。在“Closure”示例中,只需从开头删除“var startUpload =”,该函数将被完全封闭,在全局级别无法访问。在实践中,许多人更喜欢公开一个变量,其中包含对其他所有内容的引用 (2认同)

Nos*_*dna 6

有时在 JavaScript 中使用全局变量是有意义的。但是不要让它们像那样直接挂在窗户上。

相反,创建一个“命名空间”对象来包含您的全局变量。对于奖励积分,把所有东西都放在那里,包括你的方法。


Cha*_*ion 5

window.onload = function() {
  var frm = document.forms[0];
  frm.target = "postMe";
  frm.onsubmit = function() {
    frm.onsubmit = null;
    var uploader = new LazyFileUploader();
    uploader.startUpload();
    return false;
  }
}

function LazyFileUploader() {
    var uploadCount = 0;
    var total = 10;
    var prefix = "FileUpload";  
    var upload = function() {
        var fil = document.getElementById(prefix + uploadCount);

        if(!fil || fil.value.length == 0) {    
            alert("Finished!");
            document.forms[0].reset();
            return;
         }

        disableAllFileInputs();
        fil.disabled = false;
        alert("Uploading file " + uploadCount);
        document.forms[0].submit();
        uploadCount++;

        if (uploadCount < total) {
            setTimeout(function() {
                upload();
            }, 100); 
        }
    }

    this.startUpload = function() {
        setTimeout(function() {
            upload();
        }, 100);  
    }       
}
Run Code Online (Sandbox Code Playgroud)