Javascript 的 arguments對象

    昨天與突然想起一個參數callee, 放狗搜了半天,最後感謝kejun給的developer.mozilla.org.呵呵 , 主要是想在JS完美實現可變參數問>題。
    首先介紹下Arguments對象,以下摘自core javascript 1.5 reference
    The arguments object is a local variable available within all functions; arguments as a property of Function can no longer be used. You can refer to a function's arguments within the function by using the arguments object. This object contains an entry for each argument passed to the function, the first entry's index starting at 0.
    恩,很明顯,通過argument我們可以很方便的實現可變參數函數
    var add = function(){
    var sum = 0;
    for each (var item in arguments){
            sum += item;
         }
     document.write(sum); // 一個任意數目Integer求和的簡單例子
     }
    當然PHP和C++也有類似,PHP中有func_get_args, func_get_arg, func_num_args 等系列參數
    C++中有va_list, va_start, va_end 當然,C/C++中的又比較複雜了,等我有時間研究研究再說。 :)
    最後我要通過arguments對象的callee屬性來實現js的匿名函數遞歸。。
    對於callee,以下摘自core js 1.5 reference
    arguments.callee allows anonymous functions to refer to themselves, which is necessary for recursive anonymous functions.
    可見,callee主要就是用來做匿名recursive的,嘿嘿,例子如下
     function factorial(n){
      return function(n){
         if(n == 1) return 1 ;
        else return n * arguments.callee(n-1);
       };
    }
    上面的callee引用了匿名的階乘函數本身。 使用factorial()(8)調用求8的階乘,返回40320..
   恩,昨天終於弄清了ecma 262 是什麼東東, 以及又發現一些很有趣的東西在js1.6 1.8 :)

 
發佈了31 篇原創文章 · 獲贊 9 · 訪問量 14萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章