javascript - 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);
}
})();
解决方案
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.
推荐阅读
- reference - 如何在 libreoffice 的另一张纸上动态引用单元格?
- nginx - 代理服务返回 HTTP 202 时的反向代理
- python - Pandas - 在子集数据帧上调用用户定义的函数
- sql - 显示 case 表达式中的空白行
- azure - 重新部署 Azure 部署槽
- android - 如何避免在每次 CI 运行时对 aar 依赖项运行 jetifier 转换
- visual-foxpro - 如何从外部 .scx 表单运行 .exe 中包含的表单 Visual foxpro
- powershell - 无法使用 powershell.exe 运行 -Command 开关内的代码
- java - Lombok 构建器包范围
- postgresql - 在 Postgres 中使用 Serializable 事务级别的意外失败