2017-07-04 42 views
0

這裏是我的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都是一個單獨的動畫,並且具有不同的功能,儘管它們可能會共享相同的元素。但是,我想知道這是否是一種好的做法。我應該在主函數中聲明公共變量,以便它們可以位於所有子函數的執行上下文中?另外,請突出顯示任何看起來不太好或不太好的做法。謝謝

+2

這不是壞習慣,但是,例如'var body = document.querySelector('body');'可以簡單寫成'var body = document.body;' –

+0

不知道那個謝謝! –

回答

0

變量最後只有它們被定義的範圍。所以,即使你的變量從你的DOM中獲得了相同的值,只要它們在範圍內(在這種情況下,只要你的功能正在執行)。
別擔心。

0

在JavaScript中,var被提升到功能級別,所以它的作用範圍在於該功能。由於你在不同的函數中使用了相同的變量名,所以你很好,因爲它們存在於不同的作用域中。

而@theRemix和@Bergi指出,除了範圍界定之外,如果變量在每個匿名函數中表示相同的數據,則考慮重構以提高可讀性和代碼維護。

2

正如其他人所說,這是很好的,因爲功能範圍,但是,你應該知道,這是更好的做法,把他們的iife之外這兩條線(約4號線)

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

這樣的js只執行一次查找,而不是3次。這緩存了可以提高性能的dom查找。

+1

這幾乎不會提高性能,dom查找是如此便宜,無論它發生一次還是三次都無所謂。不過,它會改善代碼質量,因爲它減少了重複。 – Bergi

相關問題