用于递归的命名函数表达式

Named Function Expression for recursion

本文关键字:函数 表达式 递归 用于      更新时间:2023-09-26

正如许多人建议的那样,命名函数表达式的用法之一是递归地调用它自己。然而,似乎在Chrome控制台,没有名称的函数表达式仍然可以这样做。

编辑:我知道这将是stackoverflow,然而,我希望输出像a() is not a function而不是Uncaught RangeError:最大调用堆栈大小超过(…)。

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

下面带有名称的函数表达式应该会给我一个未捕获的RangeError: Maximum call stack size exceeded(…).

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

编辑2:在这个链接https://developer.mozilla.org/en/docs/web/JavaScript/Reference/Operators/function中,它说"如果你想在函数体中引用当前函数,你需要创建一个命名函数表达式。"然而,在我看来,该语句不是真的,因为您仍然可以在函数体内部引用当前函数,而无需为其分配函数标识符

由于没有限制递归的条件,您将达到堆栈限制。

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

这是一个非常古老的线程,但我会张贴类似的东西,在Kumar Chetan Sharma, Stoyan Stefanov和Ved Antani所著的《Javascript:面向对象编程》一书中有一个声明它是这样说的:函数声明不能有递归调用这种说法是错误的,或者缺乏更全面的解释,因为这仍然有效。

var facto = function(n){
    if(n<=1) return 1;
    return n * facto(n - 1);
}
console.log(facto(3)) // 6