Function Self Reference

This is actually a frustration of mine, because you used to be able to use arguments.callee which would get you a reference to the function. As someone else mentioned, this is no longer possible.

There is a pattern emerging for this... and that is to name the function yourself as well as assign it. It looks like this:

my_obj.myfunc = function foo(arg1, arg2) {
     // do stuff
     foo.call(this, new_arg1, new_arg2);
}

This way you can reference the named function and go about your business. Note that you do have to use the .call syntax if you want to call it as a method (so that this has meaning) but apart from that, it's pretty straightforward.

Another option is to do a truly functional approach, where you pass the object to be operated on to a function:

function foo(obj, arg1, arg2) {
    // do stuff
    // call recursively:
    foo(obj, new_arg1, new_arg2);
}

// assign as method:
my_obj.foo = function(arg1, arg2) { 
     foo(this, arg1, arg2);
}

It could be argued that this is better and more flexible. I think it's a matter of taste, really.


I cannot think of a case where a named function-expression cannot substitute for an anonymous function-expression. So I would suggest naming the function if you are going to call it from within itself (i.e., if you are going to use recursion):

function myFunc(someArg) {
    ...
    ...
    myFunc(someNewArg);
}

This works even if it is a reference:

var myFunc = function(someArg) {
    ...
}

You can even use a recursive IIFE (immediately-invoked function expression) if you don't want to pollute the namespace:

(function myFunc(arg) {
    ...
    myFunc(someOtherArg);
})(0); //some initial value

Furthermore, doing something like this:

someOtherFunction(function myFunc(arg) {
    ...
    myFunc(otherArg);
});

Also works and won't pollute the namespace.

Tags:

Javascript