2015-10-05 59 views
0

正如許多人所建議的,命名函數表達式的用法之一是遞歸調用自身。但是,似乎在Chrome控制檯中,沒有名稱的函數表達式仍可以這樣做。我知道這將是stackoverflow,但是,我期望輸出像a() is not a function,而不是未捕獲RangeError:超過最大調用堆棧大小(...)。用於遞歸的命名函數表達式

var a = function() { 
     a(); 
     } 
a(); 

以下帶名稱的函數表達式應該給我一個Uncaught RangeError:超出最大調用堆棧大小(...)。

var a = function a() { 
      a(); 
     } 
a(); 

編輯2: 在這個環節https://developer.mozilla.org/en/docs/web/JavaScript/Reference/Operators/function,它說,「如果你想引用當前函數的函數體裏面,你需要創建一個名爲函數表達式。」然而,在我看來,這種說法是不正確的,因爲你仍然可以參考函數體內的當前功能不分配功能標識它

任何想法,將不勝感激

+0

而你的問題是....? – Ionut

+0

感謝您的評論,也許我沒有明確提出我的問題。我的問題是因爲'沒有名稱的函數表達式'可以自己遞歸調用,爲什麼我們需要一個'命名函數表達式' –

+0

[var functionName = function(){} vs function functionName(){}](http: //stackoverflow.com/questions/336859/var-functionname-function-vs-function-functionname) – Ionut

回答

3

你到達因爲沒有限制遞歸的條件,所以棧限制。

var a = function (i) { 
     console.log(i); 
     if (i >= 10) { 
      return; 
     } 
     else { 
      a(++i); 
     } 
} 
a(0); 

上面是一個更好的例子來顯示這個遞歸的實際工作示例。注意這裏是否有一個檢查是否調用遞歸函數。輸出將是以下:

0 
1 
2 
3 
4 
5 
6 
7 
8 
9 
10 

還可以具有在分析時成功地定義此邏輯:

function a (i) { 
     console.log(i); 
     if (i >= 10) { 
      return; 
     } 
     else { 
      a(++i); 
     } 
} 
a(0); 

對於函數定義的範圍,本實施例示出了當a()將被定義爲:

if (typeof a === 'undefined') { 
    console.log('a is undefined before the definition'); 
} 
else { 
    console.log('a is defined before the definition'); 
} 

var a = function() { 
    if (typeof a === 'undefined') { 
    console.log('a is undefined inside of a'); 
    } 
    else { 
    console.log('a is defined inside of a'); 
    } 
} 

a(); 

if (typeof a === 'undefined') { 
    console.log('a is undefined after the definition'); 
} 
else { 
    console.log('a is defined after the definition'); 
} 

這段代碼的輸出如下:

a is undefined before the definition 
a is defined inside of a 
a is defined after the definition 
+0

感謝您的回覆。我的意思是'var a = function(){a(); }'是一個沒有名字的函數表達式,它是一個匿名函數,所以它不應該在其函數中引用自身。我期望像()這樣的輸出不是函數 –

+0

@XuzhengWang看到我的編輯,這應該解釋爲什麼這是可能的。 –

+0

非常感謝,我的問題在於第二個輸出,爲什麼a被定義在a裏面。在此鏈接https://developer.mozilla中。org/en/docs/web/JavaScript/Reference/Operators/function,它說:「如果你想引用函數體內的當前函數,你需要創建一個命名函數表達式。」然而,在我看來,這個陳述是不正確的,因爲你仍然可以在函數體內引用當前函數而不用爲它分配函數標識符。 –