这几天参加面试,有个关于递归的问题,之前在红皮书中遇到过,看过也写过代码,但是时间长了不用就会忘记,翻书肯定没有自己记住效率高;
首先解释一下为什么这么写;
//因为函数的本质是一个对象,fun是声明在栈内存中,其中保存一个地址,系统通过地址可以在堆中找到一个Function的对象;
function fun(prop){
if(prop < 100){
return prop;
}else{
fun(prop+1)
}
}
let method = fun;
fun = null;
method(12) //报错,fun不是一个函数;
所以为了代码的健壮不建议写这样的代码,往往报错后,一脸懵逼;
一般在js中有两种递归的写法:
如果不是在严格模式下,这样写是可以的;
//使用arguments.callee 属性
function fun(prop){
if(prop < 100){
return prop;
}else{
arguments.callee(prop+1) //rguments.callee === fun
}
}
ley method = fun;
method(99); //不会报差
在严格模式下.arguments.callee 不可用,
强烈建议用该写法;
//命名函数表达式
let fun = (function f(prop){
if(prop > 100){
return prop
}else{
return f(prop+1)
}
})