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