javascript - 多次声明同一个变量是一种好的做法

标签 javascript

这是我的 JavaScript 代码:

(function(){
"use strict";
document.addEventListener("DOMContentLoaded",animations); /*on content loaded */


function animations() {


/*start of animation for the toggle navigation button in smaller view ports*/
(function () { 

    var button = document.getElementById('nav-icon');
    button.addEventListener('click', function(){
        if (this.classList.contains('active')===true) {
            this.classList.remove('active');
        }
        else {
            this.classList.add('active');
        }
    })

})();  /*End of the toggle navigation animation*/

/*Start of  scrolling side navigation for smaller view ports*/

(function(){

        var button = document.getElementById('nav-icon');
        var body = document.querySelector('body');
        button.addEventListener('click', function(){
        if (this.classList.contains('active')===true) {
            body.classList.add('active-nav');
        }
        else {
            body.classList.remove('active-nav');
        }

    });

    })(); /*End of scrolling side navigation*/


(function () {
        // body...
        var media = window.matchMedia("(min-width: 992px)");
        var body = document.querySelector('body');
        var button = document.getElementById('nav-icon');
        window.addEventListener('resize',function(){

            if (media.matches) {

                    body.classList.remove('active-nav');

                    if (button.classList.contains('active')===true) {

                        button.classList.remove('active');
                    }

                }


        });

    })();


};

})();

正如您所看到的,我在代码中多次声明了具有完全相同值的变量,但它们位于不同的函数中。每个 iife 都是一个单独的动画,并且具有不同的功能,尽管它们可能共享共同的元素。但是,我想知道这是否是一个好的做法。我是否应该在主函数中声明公共(public)变量,以便它们可以位于所有子函数的执行上下文中?另外,请突出显示任何看起来不好或不是好的做法的内容。谢谢

最佳答案

正如其他人所说,由于函数范围的原因,这很好,但是,您应该知道,最好的做法是将这两行移到其 iife 之外(大约第 4 行)

var button = document.getElementById('nav-icon'); 
var body = document.querySelector('body');

这样js只执行一次查找,而不是3次。这会缓存 dom 查找,从而提高性能。

关于javascript - 多次声明同一个变量是一种好的做法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44896822/

相关文章:

javascript - 如何在 Next.js (SSR) 上检测 Internet Explorer?

javascript - 如何获取点击图像的img src

javascript - HTML。隐藏/显示下拉菜单取决于是否在另一个下拉菜单上选择了一个选项

javascript - 如何在一页中定义两个 Angular 应用程序/模块?

javascript - 删除javascript数组中的重复键值对

javascript - 无法读取属性样式错误

javascript小算法来计算价格

javascript - 当我在 Nodejs+Express 中使用 Passport 进行用户身份验证时,发生了奇怪的事情

javascript - 传递动态名称选择器不起作用

javascript - 现在是否需要使用 getElementBy* 方法