您现在的位置是:首页 > 电脑技术查询 > web开发

深入懂得javascript之arguments

编辑:chaxungu时间:2022-10-10 23:23:37分类:web开发

深入理解javascript之arguments
写道本文转自:http://blog.csdn.net/mevicky/article/details/47903457

如果转载,请写明出处
 本文介绍arguments属性。  每一个函数在定义的时候都会有一个内置的arguments属性,这个arguments属性类似数组但又不是数组。它具有数组的访问方式和length属性,却又有caller,callee等属性。  我们来举一个arguments的使用例子:var func = function(a,b){  document.write(a+' '+b+' '+"<br>");  document.write(arguments[0]+' '+arguments[1]+' '+arguments[2]+' '+"<br>");}func(1,2,3);结果为:1 2 1 2 3可以看到,我们可以通过arguments来访问函数中的参数。但是可以发现一点,即使形参中只定义了两个,而实参出现三个,arguments也可以访问到。这是怎么回事呢?这里我们就需要介绍一下arguments的属性了。caller对于函数来说,caller 属性只有在函数执行时才有定义。假如函数是由顶层调用的,那么 caller 包含的就是 null 。假如在字符串上下文中使用 caller 属性,那么结果和 functionName.toString 相同,也就是说,显示的是函数的反编译文本。但是由于caller在后续版本会被弃用,这里就不详细介绍了。calleecallee 属性是 arguments 对象的一个成员,他表示对函数对象本身的引用,这有利于匿名函数的递归或确保函数的封装性。callee拥有length属性,这个属性有时候用于验证还是比较好的。arguments.length是实参度,arguments.callee.length是形参长度,由此能够判断调用时形参长度是否和实参长度一致。  看下面实例:function func(a,b){  document.write(a+' '+b+' '+"<br>");  document.write(arguments[0]+' '+arguments[1]+' '+arguments[2]+' '+"<br>");  document.write(arguments.length+"<br>");//实参个数  document.write(arguments.callee.length+"<br>")//形参个数}func(1,2,3);结果为:  1 2  1 2 3  3  2callee还有一个作用就是用来调用函数自身,用法如下:function commonParentNode(oNode1, oNode2) {    if(oNode1.contains(oNode2)){        return oNode1;    }else if(oNode2.contains(oNode1)){        return oNode2;    }else {        return arguments.callee(oNode1.parentNode,oNode2);//递归调用    }}通过arguments.callee实现递归。

 

布瑞泽的童话-博客 写道http://blog.csdn.net/mevicky/article/details/47903457