1. 程式人生 > >關於arguments物件的一些用法

關於arguments物件的一些用法

arguments物件簡介

arguments 是一種類陣列物件,它只在函式的內部起作用,並且永遠指向當前函式的呼叫者傳入的所有引數,arguments類似Array,但它不是Array。

1.使用arguments來得到函式的實際引數。
arguments[0]代表第一個實參
ep:

function test(a,b,c,d) {
    alert(test.length);  //4
    alert(arguments.length);    //2
    if(test.length == arguments.length) {  //判斷形參與實參是否一致
        return
a+b; } } test(1,2);

2.arguments物件的callee和caller屬性
(1).arguments.callee指向函式本身
function test(a,b) {}
arguments.callee 即為 test 函式本身;
arguments.callee.length 即為函式的形參個數 2

(2).arguments.callee.caller 儲存著呼叫當前函式的函式引用(若函式在全域性作用域中執行,caller則為 null)
ep:

function add(x,y) {
    console.log(arguments.callee.caller);
}
function
test(x,y)
{ add(x,y); } test(1,2); //結果為:function test(x,y) {add(x,y);}

此時,test()在函式內部呼叫了ad(0函式,所以arguments.callee.caller則指向了test()函式。

3.arguments物件用的最多的,還是遞迴操作。
ep:

function fact(num) {
    if(num < 1)
      return  1;
    else
   // return num*fact(num-1);  //(1)
    return num*arguments.callee(num-1
); //(2) } var F = fact; alert(F(5)); //120 fact = null; alert(F(5)); //若使用(1)來實現fact()遞迴,則會報錯。fact is not a Function ;若使用(2)來實現遞迴,則可以輸出120