javascript中的幾個內置函數arguments, callee, caller, this, apply(), call()

arguments, caller, callee, this都是用在函式(function)內的特殊內定物件。而apply()及call()則是用來呼叫函式的不一樣做法。javascript

  • arguments
    可用來取得function傳入的實際變數Array。這個變數特別適合用在撰寫」多形」(Polymorphism)函式上,便可以根據不一樣的傳入參數作不一樣的處理。
    範例一 加總函數
    function sum() {
    
    var total = 0;
    
    for( var i=0; i<arguments.length; i++ ) {
    
    total += arguments[i];
    
    }
    
    return total;
    
    }
    
     
    
    // 測試
    
    log( sum() );               // 結果 = 0
    
    log( sum(1, 2) );             // 結果 = 3
    
    log( sum(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) ); // 結果 = 55

    範例二 – 自我介紹函數html

    function introduce (){
      var msg = '';
      var callback = null;
      for(var i=0;i<arguments.length;i++){
        var x = arguments[i];
        if(typeof x  == 'string'){
          msg += "我叫"+arguments[i];
        }
        if(typeof x  =='number'){
          msg += "今年"+arguments[i]+"歲";
        }
        if(typeof x  =='function'){
          callback = arguments[i];
        }
      }
      
      if(callback != null){
        callback(msg);
      }else{
        alert(msg);
      }
        
     
    }
    introduce('Harry')                    //我叫Harry
    introduce('Harry',26)                 //我叫Harry今年26歲
    introduce('Harry',26,function(msg){   //我叫Harry今年26歲 這個是自定義回調函數!
      alert(msg+" 這個是自定義回調函數!")
    })

     

  • callee
    此為arguments的屬性之一,可取得被call function自己。
  • caller
    可用來取得call該function的來源物件。
  • this
    指到函數的擁有者(Owner)。
  • apply()與call()
    apply與call兩者自己的功能相同,均可以用來特別指定被call function中的this。
    不一樣之處在於傳入參數的寫法不一樣:
    apply( thisArg, argArray ); // 第二個參數必須是個Array,否則會產生參數型態錯誤的Error
    call( thisArg[, arg1, arg2…] );

如下範例將秀出callee, caller, this及apply(), call()的用法java

function methodA(p1,p2,p3){
  console.log('=======start==========');
  console.log(arguments);       // 實際傳入的參數
  console.log(arguments.callee);//指到methodA
  console.log(arguments.callee.caller);//指到call methodA的object
  console.log('宣告參數長度'+arguments.callee.length);
  console.log('實際參數長度'+arguments.length);
  console.log(this);
  console.log(p1);
  console.log(p2);
  console.log(p3);
}

function handleCaller(){
  methodA('XXX','YYY');
  methodA.apply(handleCaller,['XXX','YYY']);//指定this object
}
                              
 function init(){
  handleCaller();
  methodA.call(handleCaller,'XXX','YYY');//指定this object
 }
 init()

結果:
注意到第一個結果區塊的this指到window物件了,而其它兩個執行結果則指到handleCaller
而第三個結果區塊的function caller指到init,其它兩個執行結果則指到handleCallerapp

以上範例中會使用到的 log function – 用於輸出文字到Firebug或Chrome, IE8的console函數

function log(msg){
   if(window.console){
     console.log(msg);
   }
 }

參考:
http://www.ijavascript.cn/jiaocheng/caller-callee-call-apply-464.html
http://blog.darkthread.net/blogs/darkthreadtw/archive/2009/03/11/js-this-and-closure.aspx
http://blog.darkthread.net/blogs/darkthreadtw/archive/2009/04/10/js-func-apply.aspxthis

相關文章
相關標籤/搜索