2013-05-17 108 views
1

如何在已有函數上添加函數?獲取「RangeError:超出最大調用堆棧大小」錯誤

我使用下面的方法,它給了我錯誤的resources.onload

resource = document.getElementById(this.id); 

    if (resource && resource.getAttribute('data-loading')) 
    {   
     onloadOthers = resource.onload; 
     onloadThis = this.onComplete.bind(this); 

//following line give error 

     resource.onload = function() { // callback loops again and again!!!!!! 
      if (typeof onloadOthers == "function") 
       onloadOthers(); 
      onloadThis(); 
     }; 

     return; // just added another callback, no need to add it again. 
    } 
    else if (resource) 
    {   
     this.onComplete(); 
     return; // already exist 
    } 

    if (this.type == "js") 
    { //if filename is a external JavaScript file 
     var code = document.createElement('script'); 
     code.setAttribute("type", "text/javascript"); 
     code.setAttribute('data-loading', 'yes'); 
     code.setAttribute("src", this.file); 
     code.onload = this.onComplete.bind(this); 
     code.onreadystatechange = code.onload; // ie fix 
    } 
+0

該錯誤通常意味着一個永無止境的循環 – HMR

+0

是的,我知道這一點。我該如何解決它?我想在新的回調之上添加以前的回調。所以他們都被觸發了。 – Basit

+1

'onloadOthers'可能會導致無限遞歸。確保'unloadOthers'變量包含在新的閉包中。 –

回答

1

移動的onloadOthersresources變量在一個新的閉包,由前綴的var關鍵字。

目前,代碼「回收」這些(全局)變量,因爲他們宣佈非本地範圍:

var onloadOthers; 
function func() { 
    onloadOthers = ...; 
    resource.onload = function() { 
     onloadOthers(); // Calls the global `onloadOthers` function. 
    }; 
} 
func(); // Defines `onloadOthers` 
func(); // Overwrites `onloadOthers` 

由變量移動到本地範圍,功能的所有實例將有一個「自己的」onloadOthers變量,它可以解決問題。

如果您想了解更多關於此主題的內容,請閱讀How do JavaScript closures work?

相關問題