【问题标题】:Named Function Expression for recursion递归的命名函数表达式
【发布时间】:2015-10-05 13:43:49
【问题描述】:

正如许多人所建议的,命名函数表达式的用途之一是递归调用自身。但是,在 Chrome 控制台中,没有名称的函数表达式似乎仍然可以这样做。

编辑: 我知道这将是 stackoverflow,但是,我希望输出类似于 a() is not a function 而不是 Uncaught RangeError: Maximum call stack size exceeded(...)。

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

以下带有名称的函数表达式应该给我一个 Uncaught RangeError: Maximum call stack size exceeded(...)。

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

编辑 2: 在此链接https://developer.mozilla.org/en/docs/web/JavaScript/Reference/Operators/function 中,它表示“如果要在函数体内引用当前函数,则需要创建一个命名函数表达式。”。但是,在我看来,这种说法并不正确,因为您仍然可以在函数体内引用当前函数而无需为其分配函数标识符

任何想法将不胜感激

【问题讨论】:

  • 你的问题是......?
  • 感谢您的评论,也许我没有把我的问题说清楚。我的问题是,既然function expression without name 可以递归调用自己,为什么我们需要named function expresion
  • 考虑表达式是否没有赋值给变量; someCallback(function a() { a(); })someCallback(function () { ??? })
  • 所以,当你打电话给a() - a 已经起作用了:-) 所以一切都正确

标签: javascript


【解决方案1】:

您正在达到堆栈限制,因为没有限制递归的条件。

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

这个sn-p的输出如下:

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

【讨论】:

  • 感谢您的回复。我的意思是var a = function () { a(); }是一个没有名字的函数表达式,它是一个匿名函数,所以它应该不能在它的函数内部引用自己。我希望像 a() 这样的东西不是输出中的函数
  • @XuzhengWang 查看我的编辑,这应该可以解释为什么会这样。
  • 非常感谢,我的问题在于第二个输出,为什么 a 在 a 中定义。在此链接developer.mozilla.org/en/docs/web/JavaScript/Reference/… 中,它表示“如果要在函数体内引用当前函数,则需要创建一个命名函数表达式。”。但是,在我看来,这句话并不正确,因为您仍然可以在函数体内引用当前函数,而无需为其分配函数标识符。
  • @XuzhengWang,实际上你指的不是self函数,而是变量a,所以如果你给它分配另一个值,它会破坏工作:-)
猜你喜欢
  • 1970-01-01
  • 2011-03-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-05-16
  • 2017-12-09
  • 2012-01-22
  • 1970-01-01
相关资源
最近更新 更多