Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to refer to the current function?

I am writing several similar versions of a certain recursive function, for comparison purposes. My functions look like this:

function rec1(n) {
    /* some code */

    rec1(n-1);
}

Then, to create another version, I copy & paste and get:

function rec2(n) {
    /* some other code */

    rec2(n-1);
}

etc.

Instead of having to change the name of the function in each version, I wonder if there is some way to refer to the "current function" (just as in a Unix script it is possible to refer the the "current script" with the $0 variable), so that I can write:

function rec1(n) {
    /* some code */

    $this_function$(n-1);
}
like image 418
Erel Segal-Halevi Avatar asked Nov 27 '25 05:11

Erel Segal-Halevi


1 Answers

You could use arguments.callee, but it's deprecated.

Better just name the functions, and give them all the same names:

var rec1 = function rec(n) {
    /* some code */

    rec(n-1);
};
var rec2 = function rec(n) {
    /* some other code */

    rec(n-1);
};

… where rec is scoped the current function, and points to the current function.

like image 94
Bergi Avatar answered Nov 29 '25 18:11

Bergi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!