递归

来源:互联网 发布:it桔子网 编辑:程序博客网 时间:2024/05/29 09:12

*本文来自《javaScript高级程序设计》的学习笔记


递归函数是在一个函数内部通过名字调用自身的情况下构成的

例如:

//####################Test01 begin#################function factorial(num) {    if (num <= 1) {        return 1;    } else {        return num * factorial(num - 1);    }}var anotherFactorial = factorial;factorial = null;alert(anotherFactorial(4));//####################Test01 end#################/** * 以上代码先把factorial()函数保存在变量anotherFactorial中; * 然后将factorial置为null,结果指向原始函数的引用只剩下一个; * 在接下来调用anotherFactorial()时,由于必须执行factorial(),而factorial已经被置为null,不再是函数,所以就会导致错误 * 在这种情况下,使用arguments.callee 可以解决这个问题。 * arguments.callee 是一个指向正在执行的函数的指针,因此可以用它来实现对函数的递归调用,例如: *///####################Test02 begin#################function factorial2(num) {    if (num <= 1) {        return 1;    } else {        return num * arguments.callee(num - 1);    }}var anotherFactorial2 = factorial2;factorial2 = null;alert(anotherFactorial2(4));//####################Test02 end#################/** *在严格模式下,不能通过脚本访问arguments.callee,访问这个属性会导致报错。 *这种情况下可以使用命名函数表达式来达成相同的结果,例如: *///####################Test03 begin#################var factorial3 = (function f(num) {    if (num <= 1) {        return 1;    } else {        return num * f(num - 1);    }});var anotherFactorial3 = factorial3;factorial3 = null;alert(anotherFactorial3(4));//####################Test03 end#################
*个人认为没有必要搞得这么复杂,正常是不会把已经声明的一个函数置为null

0 0
原创粉丝点击