您的位置:首页 > 移动开发

javascript中的几个内置函数arguments, callee, caller, this, apply(), call()

2016-08-26 00:00 162 查看
arguments, caller, callee, this都是用在函式(function)內的特殊內定物件。而apply()及call()則是用來呼叫函式的不同作法。

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
范例二 – 自我介绍函数
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()的用法

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,其它兩個執行結果則指到handleCaller

以上範例中會使用到的 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.aspx
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  javascript DOM WEB