js之arguments详解

本文深入解析了JavaScript中arguments对象的功能,包括其与实参的关系、类数组特性及callee属性的应用。通过实例展示了如何使用arguments实现匿名函数递归及定时器倒计时,同时介绍了caller属性的用途。

1.arguments表示传参列表,它和实参列表相对应。

function test(x){
            console.log(arguments);  //arguments=[1,2,3]
        }
        test(1,2,3)

注:arguments和形参是相映射的关系

function test(x){
            x = 2;
            console.log(arguments);  //argumnets=[2,2,3]
        }
        test(1,2,3)

如果修改x的值,arguments的值也会发生改变,同理,如果改变argumnets的值,x的值也会发生改变。
2.arguments是一个类数组
3.arguments.callee

		function test(){
            console.log(arguments.callee);
        }
        test();

arguments.callee的返回结果就是函数引用,即function test(){}

那么arguments.callee有什么作用呢?

例如我们可以利用arguments.callee拿到一个匿名函数的引用

例子:求100的阶乘

var result = (function(n){
            if(n ==1) return 1;
            return n * arguments.callee(n-1);
        }(100))

这是一种用递归的方法实现阶乘的方法,因为是用的立即执行函数,并不能拿到函数名称,所以可以通过arguments.callee来解决这个问题。

还有类似这样,用setTimeOut实现倒计时

(function (n){
    if(n==0) return;
    var args = arguments;
    console.log(n);
    setTimeout(function(){
        n--;
        arguments.callee(n);
    },1000);
})()

还有一个关于function的用法,function.caller

function test(){
            demo()
        }
        function demo(){
            console.log(demo.caller)    //function test(){}
        }
        test()

function.caller返回的是该函数被调用的环境

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值