递归函数

谁说我不能喝 提交于 2019-11-27 18:38:18

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

function factorial (num){
  if (num <= 1){
    return 1;
  } else {
    return num* factorial(num-1)
  }
}
var anotherFactorical = factorial;
console.log(anotherFactorical)
factorial = null
console.log(anotherFactorical(4))//出错

函数的名字是一个指向函数对象的指针,如果把函数的名字与函数对象本身的指向关系断开,就会出错

解决方法:

arguments.callee(指向正在执行的函数的指针)

function factorial (num){
  if (num <= 1){
    return 1;
  } else {
    return num* arguments.callee(num-1)
  }
}
var anotherFactorical = factorial;
console.log(anotherFactorical)
factorial = null
console.log(anotherFactorical(4))//24

严格模式下,不能通过脚本访问arguments.callee,访问这个属性会导致错误

可以通过命名函数表达式来达成相同的结果

var factorial = (function f (num){
  if (num <= 1){
    return 1;
  } else {
    return num* f(num-1)
  }
});
console.log(factorial)
var anotherFactorical = factorial;
factorial = null
console.log(anotherFactorical)

console.log(f())
f = null

factorial = null
console.log(f)
 console.log(anotherFactorical(4))//24

即便把函数赋值给另一个变量,函数的名字f仍然有效,递归还能正常进行

f()对外是不可见的

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!