关于arguments.callee的用途

时间:2023-03-09 13:26:28
关于arguments.callee的用途

arguments为js函数中两个隐藏属性中的一个(另一个为this)

arguments表示所有传入的参数,为类数组(array-like)类型,arguments.length表示传入参数的长度,但是没有数组类型的其他方法。

var func = function(arg1, arg2, arg3){
     alert(arguments.length); // 2 为实际调用参数的长度
     alert(arguments.callee.length);  // 3 为函数本身定义参数的长度
}

func(, );

arguments.callee表示函数体本身,通过开发者模式我们可以看到arguments.callee的属性结构和函数本身一致。

都是拥有caller length arguments name prototype _proto_这些属性的。

这样在有了callee的话,我们在使用递归时就无需通过函数名称进行函数的调用,而是直接使用该不变属性。

这样做的话有利于我们未来再修改了函数名称后的维护。

如:

var a = function(){
    count ++;
    if(count <10){
        arguments.callee();// 在a修改为其他名称时,这里无需修改
    }else{
        alert(count);
    }
};
a();

在递归时使用arguments.callee是一个有利于未来维护的好习惯。