arguments,caller,callee是函数内部隐藏的对象或属性,本文对其使用方法做简单的介绍
1.arguments
arguments是函数在被调用时创建的一个隐藏对象,在函数未被调用时arguments对象未被创建,其值为null。
arguments保存的是调用函数的实参的信息,是一个类似数组的对象,具有length属性,可以对其遍历。
function argTest(){
console.log(arguments.length)//实参的长度
console.log(arguments.callee.length)//形参的长度
for(var i = 0; i<arguments.length; i++){
console.log(arguments[i]);
}
}
console.log(argTest.arguments);//null
argTest(1,2,3);//3,0 1,2,3
从上面可以看出arguments很像数组,但是下面的代码可以检查其实质却是一个对象
(function (){
console.log(arguments instanceof Array);//false
console.log(typeof(arguments));//object
})()
2.caller
caller是一个函数被另一个函数调用时生成的属性,指向调用者。如果函数未被调用或者函数是由顶层调用的,其值都为null。
function callerTest(){
if(arguments.callee.caller){
console.log(arguments.callee.caller.toString());
}else{
console.log('this func is called by top');
}
}
console.log(callerTest.caller);//null
callerTest();//this func is called by top
function showCaller(){
callerTest();
}
showCaller();//这里显示的应该就是showCaller的反编译文本
3.callee
其实上面两小节都用到了callee,callee是arguments对象的一个成员,当函数被调用时,arguments.callee对象指向函数自身,即对自己的引用。
function calleeTest(){
console.log(arguments.callee);
}
console.log(calleeTest('calleeTest'));//calleeTest自身
try{
console.log(calleeTest.arguments.callee);
}catch(e){
throw e;//Uncaught TypeError: Cannot read property 'callee' of null at <anonymous>:6:36
}
既然callee指向函数的引用,所以我们联想到在递归调用时使用callee,但是现在不做推荐了,callee的出现其实是由于早期js没有具名函数,函数表达式里无法实现递归才添加的。
同时arguments.callee也会带来函数引用优化和尾递归优化的问题。
下面举一个斐波那契递归调用的例子,只简单了解callee的使用:
function fibs (n){
if(n===1 || n===2){
return 1;
}else{
return arguments.callee(n-1)+arguments.callee(n-2);
}
}
fibs(6);//8
4.使用限制
arguments对象目前只能在非严格模式下使用,像es6的模块中都是默认严格模式“use strict”的,所以在es6中我们只能和这些功能say bye-bye了。
大家对严格模式有什么不了解的可以看看阮一峰的这片博客 Javascript 严格模式详解