3

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);
}
Erel Segal-Halevi
  • 33,955
  • 36
  • 114
  • 183
  • 1
    `arguments.callee`, though it is forbidden in strict mode. Why not just use the name? Or you may be better of creating a function factory if the recursive call is always at the end and always has the same criteria. – cookie monster Sep 21 '14 at 16:41

1 Answers1

6

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.

mscdex
  • 104,356
  • 15
  • 192
  • 153
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • 2
    Also FWIW, [here is an explanation](http://stackoverflow.com/a/235760) of why `arguments.callee` is deprecated. – mscdex Sep 21 '14 at 17:12