用于递归的命名函数表达式
Named Function Expression for recursion
正如许多人建议的那样,命名函数表达式的用法之一是递归地调用它自己。然而,似乎在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
相关文章:
- 能够在定义函数表达式之前使用它
- 函数表达式,返回回调函数
- JavaScript中的立即调用函数表达式(IIFE)-传递jQuery
- 函数声明与函数表达式之间的性能差异
- 立即调用函数表达式(IIFE)相对于普通函数的优势
- 如何防止 JS 缩小删除命名函数表达式的名称
- Angularjs 与 coffeescript 函数表达式中断
- JavaScript 混乱中的函数表达式
- 从ES6中的函数表达式访问类作用域
- 提升作为数组项的匿名函数表达式
- Javascript Mocha测试-测试函数表达式中的函数表达式
- 函数中的JavaScript函数表达式
- Javascript闭包覆盖函数表达式
- 函数表达式的词法作用域
- 请解释一下“;立即调用函数表达式“;以及“;自调用匿名函数”;
- JavaScript 中的函数语句和函数表达式
- ng-class 的函数表达式在 ng-click 时被调用
- 如何创建名称和主体存储在不同变量中的 JavaScript 函数表达式
- Object.Prototype 方法和 IIFE(立即调用的函数表达式)中的“use strict”
- 全局范围内的函数表达式与函数声明的区别