首先上个例子:
Function factorial(num){ if(num<=1){ return 1; }else{ return num*factorial(num-1); }}
这是一个经典的递归阶乘函数,但是在js中这么调用可能会出现一些错误:例如如下代码
var anotherFactorial = factorial;factorial = null;alert(anotherFactorial)// 出错
以上代码先把factorial()函数保存在变量anotherFactorial中,然后将factorial变量设置为null,结果指向原始函数的引用只剩下一个。但再接下来调用anotherFactioral()时候,由于必须执行factorial函数,而factoial已经不再是函数,所以就会导致错误,再这种情况下,使用arguments.callee可以解决这个问题。
arguments.callee是一个指向正在执行的函数的指针,因此可以用来实现对函数的递归调用。
例如:
function factorial (num){ if(num){ return 1; }else{ return num*arguments.callee; }}
严格模式下写法:
var factorial = (function f(){ if(num<1){ return 1; }else{ return num*f(num-1); }})
js是单线程语言,但他允许通过设置超时调用和间歇时间来调度代码在特定的时刻执行。前者是在指定的时间过后执行代码,而后者则是每隔指定的时间就执行一次代码。
参数:要执行的代码 和 以 毫秒表示时间
//不建议传字符串,传递字符串可能导致性能损失 setTimeout("alter('hello word')", 1000);//推荐方式setTimeout(function(){ alter("Hello world");},1000)setInterval(function(){ alter("Hello world");},1000)
注意点:结束
实际应用中:
var num = 0, max = 0;function incrrmentNumber{ num++; if(num < max){ setTimeout(incrrmentNumber,500); }else{ alert("Done"); }}setTimeout(incrrmentNumber,500);
如果像上面那样使用超时调用,则可以避免这一点。所以不要使用间歇调用;
以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,同时也希望多多支持!