Sergio Romero
Sergio Romero

Reputation: 6607

Is arguments.callee still safe to use or is there a better alternative

I am analyzing some code from a book I am reading and there is a small piece that confuses me a little bit:

//... some code

setTimeout(function(){
   //...some code
   if(some condition)
      setTimeout(arguments.callee, 0);
}, 0);

What is a little confusing for me is that the same book mentions that the "callee" property has been deprecated and that it should not be used unless strictly necessary (I am paraphrasing). So I am wondering if this is one of those cases or if there could be a better way to accomplish the recursive call. Somewhere on the internet I read that the following may accomplish the same thing:

//... some code

setTimeout(function myRecursiveFunction(){
   //...some code
   if(some condition)
      setTimeout(myRecursiveFunction, 0);
}, 0);

Is this correct? Is there yet a better way to approach this? Is it safe and ok to keep using arguments.callee?

Thank you for any clarification.

Upvotes: 1

Views: 439

Answers (2)

SLaks
SLaks

Reputation: 887509

arguments.callee is deprecated and may be removed.
It also makes the code harder for the browser to optimize.

Your second approach is correct.
When you create an anonymous function (function expression) with a name, that name becomes accessible to the code within the function expression.

Upvotes: 1

ninjagecko
ninjagecko

Reputation: 91092

The second approach is best. What it actually does is it "hoists" the function declaration to the top of the nearest enclosing scope (the function in which this was defined), and names the function "myRecursiveFunction".

The alternative would be creating an anonymous scope like so:

setTimeout(
    (function(){
        var myRecursiveFunction = function() {
            console.log(myRecursiveFunction);
        };
        return myRecursiveFunction
    }),
    1000
)

or perhaps using a fixedpoint combinator from functional programming.

Upvotes: 1

Related Questions