码迷,mamicode.com
首页 > 编程语言 > 详细

JavaScript学习笔记(八)--- 函数表达式

时间:2014-09-09 10:42:48      阅读:220      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   io   使用   java   ar   strong   div   

1.递归

实现一:

function factorial(num){
    if(num<=1){
        return 1;
    }else{
        return num*factorial(num-1);
    }
}
alert(factorial(4)); //24

但给factorial重赋值时,再调用就会出错。

var anotherFactorial = factorial;
factorial = null;
alert(anotherFactorial(4)); //TypeError: factorial is not a function

实现二:

使用arguments.callee解决上面问题。

function factorial(num){
    if(num<=1){
        return 1;
    }else{
        return num*arguments.callee(num-1);
    }
}
alert(factorial(4)); //24

修改factorial,再调用

var anotherFactorial = factorial;
factorial = null;
alert(anotherFactorial(4)); //24

实现三:

在严格模式下,不能通过脚本访问arguments.callee。解决办法,使用命名函数表达式。

var factorial = (function f(num){
    if(num<=1){
        return 1;
    }else{
        return num*f(num-1);
    }    
});

alert(factorial(4)); //24

以上代码创建了一个名为f()的命名函数表达式,然后将它赋值给变量factorial。

把函数赋值给另一个变量,函数的名字f仍然有效。这种方式在严格模式和非严格模式下都行得通。

var anotherFactorial = factorial;
factorial = null;
alert(anotherFactorial(4)); //24

2.闭包

 

JavaScript学习笔记(八)--- 函数表达式

标签:style   blog   color   io   使用   java   ar   strong   div   

原文地址:http://www.cnblogs.com/yanyangbyou/p/3961276.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!