2013-05-17 2 views
1

어떻게 기존 함수 위에 함수를 추가 할 수 있습니까?"RangeError : 최대 호출 스택 크기 초과"오류 받기

나는 다음과 같은 방법을 사용하고 있는데이 var 키워드를 접두사로, 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 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?을 읽어보십시오.

관련 문제