Callee and caller in function

Source: Internet
Author: User
Tags addchild

Inside the function, arguments is a class array object that holds the function arguments.

This is a brief summary of the 2 attributes that exist within arguments: Callee,caller callee:

Callee: is a pointer to the function that owns the arguments object,

Example:

function Cool () {
    console.log (Arguments.callee);
}

Cool ();

The results are printed (chrome):
Ƒcool () {
 console.log (Arguments.callee);
}

Using the characteristics of the callee pointer, we can use logical processing such as factorial:

Here is the most basic common factorial,

function Add (num) {
    if (num<=1) {return
        1;
    } else{return
        num * Add (NUM-1);
    }

Add (a);    3628800

The biggest problem with factorial above is that the execution within the function is coupled to the name add of functions, which can be arguments.callee to eliminate this coupling:

function Add (num) {
    if (num <= 1) {return
        1;
    } else{return
        num * Arguments.callee (NUM-1);
    }
Add (a);    3628800
Caller:

Caller retains a reference to the function that called the current function.

function Add () {
    addChild ();
}

function AddChild () {
    console.log (addchild.caller);
}

Add ();

Print results under Chrome:
Ƒadd () {
  addChild ();
}

To achieve low coupling, you can use Arguments.callee to:

function Add () {
    addChild ();
}

function AddChild (argument) {
    console.log (arguments.callee.caller);
}

Add ();

Print results under Chrome:
Ƒadd () {
  addChild ();
}

* If this function is lowered in the global scope, caller is null.

function Add () {
    console.log (arguments.callee.caller);
}

Add ();      Null
Note:Arguments.callee in strict mode will cause errors, can not be assigned to caller, or error, ECMASCRIPT5 also defined Arguments.caller, strict mode will lead to errors, not strict mode is undefined The Arguments.callee is defined to differentiate between arguments.caller and function caller attributes.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.