首页 > 解决方案 > javascript: When to store variables on the window object?

问题描述

I had to build a simple click counter using vanilla javascript during an interview on a random existing website in any section from within the Chrome console. I don't know how I did yet but is there any way to improve this? I couldn't think of anything other than using the window object to hold the counter. Is that bad to do? This seemed like the right choice at the time when I was doing it...just run a self invoking function in console that adds an click listener and attaches a clickIt function to it, which is defined inside.

(function addingClickCounter() {
    let element = document.getElementById('itemList');
    element.addEventListener('click', clickIt);
    function clickIt() {
        if (window.counter) {
            window.counter = 0
        }
        window.counter++;
        console.log(window.counter);
    }
})();

标签: javascript

解决方案


It's quite easy to just store the variable inside the addingClickCounter closure, avoiding global pollution:

(function addingClickCounter() {
    let element = document.getElementById('itemList');
    element.addEventListener('click', clickIt);
    let counter = 0;
    function clickIt() {
        counter++;
        console.log(counter);
    }
})();

Usually, you only want to deliberately set properties on the global object when you need to communicate between completely separate scripts, or when a library does it automatically to expose a namespace object (like jQuery and React). Unless you're dealing with inter-script communication, you can usually avoid global properties.


推荐阅读