递归函数

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

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()对外是不可见的

posted on 2019-08-18 15:16  嗯嗯呢  阅读(132)  评论(0编辑  收藏  举报