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

标签 javascript global-variables

我们都知道 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();
}

相关标记:

<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. -->

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

这个例子大家可以不用具体回答,我只是提供给自己想不出避免全局变量的方法的情况下引用。

最佳答案

最简单的方法是将您的代码包装在闭包中,并手动仅将全局需要的那些变量公开到全局范围:

(function() {
    // Your code here

    // Expose to global
    window['varName'] = varName;
})();

为了解决 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();
        }
    });

})();

HTML:

<iframe src="test.htm" name="postHere" id="postHere"></iframe>

不需要 <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>

每当我在 Safari、Firefox、IE 6、7 和 8 中单击提交按钮时都会触发警报。

关于javascript - 如何避免 JavaScript 中的全局变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1841916/

相关文章:

javascript - 根据下拉列表中的值更改文本框背景颜色

javascript - 如何知道两个子进程何时解析了nodejs

c++ - 外部变量和数组声明问题 C++

javascript - 如何跨 CoffeeScript 函数访问变量?

Python 套接字实现

javascript - Onclick 不应触发表单数据提交

javascript - 将鼠标悬停在图像上时 qTip 不起作用

javascript - CORS - Facebook - Passport

r - 在 R 中的并行应用中设置矩阵行中的值

ios - 我想,陷入 for 循环中,不能使用循环外设置的变量吗?