避免全局变量的正确方法

时间:2017-08-17 09:42:38

标签: javascript variables global

是否有正确的方法(ES6友好)以避免在我的JavaScript示例中使用全局变量?我看到我们可以使用函数将代码包装在闭包中吗?..

<textarea name="fileEdition" id="fileEdition" placeholder="Some content from a file, editable"></textarea>
<button id="saveFile">Save</button>

<script>
    const files = document.querySelector('#RandomFileListGotInPHP');
    const fileEdition = document.querySelector('#fileEdition');
    const saveButton = document.querySelector('#saveFile');

    function openFile() {
        fileEditionBackup = fileEdition.value;    
    }

    function saveFile() {
        console.log(`backup content before save in PHP: ${fileEditionBackup}`);
    }

    files.addEventListener('change', openFile);
    saveButton.addEventListener('click', saveFile);
</script>

感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

我无法找到反对IIFE的理由:

(function () {

    const files = document.querySelector('#RandomFileListGotInPHP');
    const fileEdition = document.querySelector('#fileEdition');
    const saveButton = document.querySelector('#saveFile');

    function openFile() {
        fileEditionBackup = fileEdition.value;    
    }

    function saveFile() {
        console.log(`backup content before save in PHP: ${fileEditionBackup}`);
    }

    files.addEventListener('change', openFile);
    saveButton.addEventListener('click', saveFile);
})();

当然,+function(){ ... }()(_=>{ ... })()也可以。