这里是我的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都是一个单独的动画,并且具有不同的功能,尽管它们可能会共享相同的元素。但是,我想知道这是否是一种好的做法。我应该在主函数中声明公共变量,以便它们可以位于所有子函数的执行上下文中?另外,请突出显示任何看起来不太好或不太好的做法。谢谢
这不是坏习惯,但是,例如'var body = document.querySelector('body');'可以简单写成'var body = document.body;' –
不知道那个谢谢! –