2012-05-23 32 views
6

が前のものに拡張のための新しい質問を開くために嫌い:再帰関数のjavascriptの復帰

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; 
     } 
    } 
} 

これは、反復= 5を返しますが未定義結果?そんなことがあるものか ?明示的にsWordを返します。返すsWordの直前に警告(sWord)していれば、「hahalollollollollol」と返されたはずです。

答えて

14

func2.call(this, sWord); 

は次のようになります。

return func2.call(this, sWord); 
0

外部関数にreturnステートメントがないため、undefinedを返します。あなたは、スタックのすべての方法を返す必要が

4

あなたは再帰の結果を返す必要があり、または他の方法では、暗黙的にundefinedを返します。次のことを試してみてください。

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); 

return func2.call(this, sWord); 
0

:)

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; 
    } 
それをシンプルに保つべきです