js中callee和caller

js中callee关键字的作用
  1. callee关键字的定义:在函数内部使用,代表当前函数的引用(名字)。

  2. 作用:降低代码的耦合度。

  3. 耦合度的定义:一处代码的修改会导致其他代码也要发生改变(耦合度高)在项目里边要开发低耦合度的代码(一处代码修改尽量少地引起其他代码的变化)。

  4. 语法结构

    function f1(){arguments.callee();}
    f1();
    

实例

<script type="text/javascript">
        function jiecheng(n){
            if(n==1){
                return 1;
            }
            //return n * jiecheng(n-1);
            //callee可以保证外部名称的变化,不会引起内部代码的修改,代码耦合度降低
            return n * arguments.callee(n-1);
        }
        //要把jiecheng名称换成其他的名字进行使用

        var jc = jiecheng; //对象赋值,其为引用传递

        jiecheng = null;  //销毁jiecheng函数对象,后期不使用了
        console.log(jc(4)); //输出24
        var jd = jc;
        jc = null;
        console.log(jd(6)); //输出720
</script>

callee返回正在执行的函数本身的引用。callee是arguments的一个属性,这个属性是一个指针,指向这个拥有arguments对象的函数,(arguments是调用函数,那么这个callee就是调用函数的啦)

caller
  1. 函数fun的caller返回调用fun的函数对象,即fun的执行环境,如果fun的执行环境为window则返回null;

    function fun(){
    	console.log(argument.callee.caller);
    	//argument.callee.caller必须写在fun中,
    	//因为argument,caller只在执行时才有效。
    }
    fun(); 
    //结果为null
    
    function a(){
        fun();
        function fun(){
            console.log(fun.caller)//这里必须写在fun里面,因为caller只有函数执行过程中才有效
        }
    }
    a();
    

    结果为: a函数
    这里写图片描述

    完整项目实例:

发布了27 篇原创文章 · 获赞 5 · 访问量 6100

猜你喜欢

转载自blog.csdn.net/systempause/article/details/104767704