2012-05-23 20 views
6

Nienawiść, aby otworzyć nowe pytanie o przedłużenie poprzedniej:javascript powrót funkcji rekurencyjnej

function ctest() { 
    this.iteration = 0; 
    this.func1 = function() { 
     var result = func2.call(this, "haha"); 
     alert(this.iteration + ":" + result); 
    } 
    var func2 = function(sWord) { 
     this.iteration++; 
     sWord = sWord + "lol"; 
     if (this.iteration < 5) { 
      func2.call(this, sWord); 
     } else { 
      return sWord; 
     } 
    } 
} 

to zwraca iteracja = 5, ale spowodować UNDEFINED? jak to możliwe ? jawnie zwracam sWord. Powinien powrócić "hahalollollollolol" i tylko dla podwójnego sprawdzenia, jeśli ostrzeżę (sWord) tuż przed sys- temem powrotu, wyświetli go poprawnie.

Odpowiedz

14

Trzeba powrócić aż do góry stosu:

func2.call(this, sWord); 

powinno być:

return func2.call(this, sWord); 
0

Twoja zewnętrzna funkcja nie ma instrukcji return, więc zwraca undefined.

4

Trzeba zwrócić wynik rekursji, albo sposób dorozumiany zwraca undefined. Spróbuj wykonać następujące czynności:

function ctest() { 
this.iteration = 0; 
    this.func1 = function() { 
    var result = func2.call(this, "haha"); 
    alert(this.iteration + ":" + result); 
    } 
    var func2 = function(sWord) { 
    this.iteration++; 
    sWord = sWord + "lol"; 
    if (this.iteration < 5) { 
     return func2.call(this, sWord); 
    } else { 
     return sWord; 
    } 
    } 
} 
1
func2.call(this, sWord); 

powinny być

return func2.call(this, sWord); 
0

keep it simple :)

your code modified in JSFiddle

iteration = 0; 
func1(); 

    function func1() { 
     var result = func2("haha"); 
     alert(iteration + ":" + result); 
    } 

    function func2 (sWord) { 
     iteration++; 

     sWord = sWord + "lol"; 
     if (iteration < 5) { 
      func2(sWord); 
     } else { 

      return sWord; 
     } 

    return sWord; 
    } 
Powiązane problemy