2016-07-04 60 views
1

下面的代碼給了一個錯誤,在某些版本的Firefox瀏覽器 - linksHandle is not defined關閉和功能hoisting-不工作在Firefox

該代碼是由在底部有一個名爲linksHandle功能的功能的。據我所知,當函數被定義的函數被調用時,該函數應該被掛起。

因此,對於事件「mMenuReady」中定義的功能應該能夠訪問它,因爲它機箱在它的執行上下文中定義的所有功能和變量。

爲什麼有些版本的Firefox需要的函數聲明(linksHandle)進行之前,爲了使「mmenu」回調包圍函數定義的?

document.addEventListener('readystatechange', function() { 
    if (document.readyState === 'interactive') { 

     if (typeof jQuery === 'function') { 
      // callback function that is invoked later by the event that is triggered -> $(window).trigger("mMenuReady") 
      $(window).on('mMenuReady', function() { 
       var links2 = Array.prototype.slice.call(document.querySelectorAll('#mm-mainMenu a')); 
       links2.forEach(linksHandle); 
      }); 
     } 

     function linksHandle(elem) { 
      // function code 
     } 
    } 
}); 

回答

1

Function declarations inside blocks只允許從ES6開始。他們吊起你的if身體內(而不是整個函數),而不是在舊版本的FF那確實實現它們,"function statements"的未懸掛(實際上completely invalid in strict mode),具有caused issues like yours

+0

如果代碼不是如果塊內,並被decalred在功能的時候了。是ES6中的內在功能? 我的問題是if語句對函數的提升有影響嗎? – user3021621

+0

是的,函數級函數聲明在函數級範圍內被掛起。 – Bergi

+0

但是在更高級的ES中,函數也會在if塊中掛起? – user3021621