js之arguments、caller、callee

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 严格模式详解


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值